home *** CD-ROM | disk | FTP | other *** search
/ Clickx 115 / Clickx 115.iso / software / tools / windows / tails-i386-0.16.iso / live / filesystem.squashfs / usr / share / perl5 / IPC / Run.pm
Encoding:
Perl POD Document  |  2010-04-01  |  134.2 KB  |  4,393 lines

  1. package IPC::Run;
  2.  
  3. =pod
  4.  
  5. =head1 NAME
  6.  
  7. IPC::Run - system() and background procs w/ piping, redirs, ptys (Unix, Win32)
  8.  
  9. =head1 SYNOPSIS
  10.  
  11.    ## First,a command to run:
  12.       my @cat = qw( cat );
  13.  
  14.    ## Using run() instead of system():
  15.       use IPC::Run qw( run timeout );
  16.  
  17.       run \@cmd, \$in, \$out, \$err, timeout( 10 ) or die "cat: $?"
  18.  
  19.       # Can do I/O to sub refs and filenames, too:
  20.       run \@cmd, '<', "in.txt", \&out, \&err or die "cat: $?"
  21.       run \@cat, '<', "in.txt", '>>', "out.txt", '2>>', "err.txt";
  22.  
  23.  
  24.       # Redirecting using psuedo-terminals instad of pipes.
  25.       run \@cat, '<pty<', \$in,  '>pty>', \$out_and_err;
  26.  
  27.    ## Scripting subprocesses (like Expect):
  28.  
  29.       use IPC::Run qw( start pump finish timeout );
  30.  
  31.       # Incrementally read from / write to scalars. 
  32.       # $in is drained as it is fed to cat's stdin,
  33.       # $out accumulates cat's stdout
  34.       # $err accumulates cat's stderr
  35.       # $h is for "harness".
  36.       my $h = start \@cat, \$in, \$out, \$err, timeout( 10 );
  37.  
  38.       $in .= "some input\n";
  39.       pump $h until $out =~ /input\n/g;
  40.  
  41.       $in .= "some more input\n";
  42.       pump $h until $out =~ /\G.*more input\n/;
  43.  
  44.       $in .= "some final input\n";
  45.       finish $h or die "cat returned $?";
  46.  
  47.       warn $err if $err; 
  48.       print $out;         ## All of cat's output
  49.  
  50.    # Piping between children
  51.       run \@cat, '|', \@gzip;
  52.  
  53.    # Multiple children simultaneously (run() blocks until all
  54.    # children exit, use start() for background execution):
  55.       run \@foo1, '&', \@foo2;
  56.  
  57.    # Calling \&set_up_child in the child before it executes the
  58.    # command (only works on systems with true fork() & exec())
  59.    # exceptions thrown in set_up_child() will be propagated back
  60.    # to the parent and thrown from run().
  61.       run \@cat, \$in, \$out,
  62.          init => \&set_up_child;
  63.  
  64.    # Read from / write to file handles you open and close
  65.       open IN,  '<in.txt'  or die $!;
  66.       open OUT, '>out.txt' or die $!;
  67.       print OUT "preamble\n";
  68.       run \@cat, \*IN, \*OUT or die "cat returned $?";
  69.       print OUT "postamble\n";
  70.       close IN;
  71.       close OUT;
  72.  
  73.    # Create pipes for you to read / write (like IPC::Open2 & 3).
  74.       $h = start
  75.          \@cat,
  76.             '<pipe', \*IN,
  77.             '>pipe', \*OUT,
  78.             '2>pipe', \*ERR 
  79.          or die "cat returned $?";
  80.       print IN "some input\n";
  81.       close IN;
  82.       print <OUT>, <ERR>;
  83.       finish $h;
  84.  
  85.    # Mixing input and output modes
  86.       run \@cat, 'in.txt', \&catch_some_out, \*ERR_LOG );
  87.  
  88.    # Other redirection constructs
  89.       run \@cat, '>&', \$out_and_err;
  90.       run \@cat, '2>&1';
  91.       run \@cat, '0<&3';
  92.       run \@cat, '<&-';
  93.       run \@cat, '3<', \$in3;
  94.       run \@cat, '4>', \$out4;
  95.       # etc.
  96.  
  97.    # Passing options:
  98.       run \@cat, 'in.txt', debug => 1;
  99.  
  100.    # Call this system's shell, returns TRUE on 0 exit code
  101.    # THIS IS THE OPPOSITE SENSE OF system()'s RETURN VALUE
  102.       run "cat a b c" or die "cat returned $?";
  103.  
  104.    # Launch a sub process directly, no shell.  Can't do redirection
  105.    # with this form, it's here to behave like system() with an
  106.    # inverted result.
  107.       $r = run "cat a b c";
  108.  
  109.    # Read from a file in to a scalar
  110.       run io( "filename", 'r', \$recv );
  111.       run io( \*HANDLE,   'r', \$recv );
  112.  
  113. =head1 DESCRIPTION
  114.  
  115. IPC::Run allows you to run and interact with child processes using files, pipes,
  116. and pseudo-ttys.  Both system()-style and scripted usages are supported and
  117. may be mixed.  Likewise, functional and OO API styles are both supported and
  118. may be mixed.
  119.  
  120. Various redirection operators reminiscent of those seen on common Unix and DOS
  121. command lines are provided.
  122.  
  123. Before digging in to the details a few LIMITATIONS are important enough
  124. to be mentioned right up front:
  125.  
  126. =over
  127.  
  128. =item Win32 Support
  129.  
  130. Win32 support is working but B<EXPERIMENTAL>, but does pass all relevant tests
  131. on NT 4.0.  See L</Win32 LIMITATIONS>.
  132.  
  133. =item pty Support
  134.  
  135. If you need pty support, IPC::Run should work well enough most of the
  136. time, but IO::Pty is being improved, and IPC::Run will be improved to
  137. use IO::Pty's new features when it is release.
  138.  
  139. The basic problem is that the pty needs to initialize itself before the
  140. parent writes to the master pty, or the data written gets lost.  So
  141. IPC::Run does a sleep(1) in the parent after forking to (hopefully) give
  142. the child a chance to run.  This is a kludge that works well on non
  143. heavily loaded systems :(.
  144.  
  145. ptys are not supported yet under Win32, but will be emulated...
  146.  
  147. =item Debugging Tip
  148.  
  149. You may use the environment variable C<IPCRUNDEBUG> to see what's going on
  150. under the hood:
  151.  
  152.    $ IPCRUNDEBUG=basic   myscript     # prints minimal debugging
  153.    $ IPCRUNDEBUG=data    myscript     # prints all data reads/writes
  154.    $ IPCRUNDEBUG=details myscript     # prints lots of low-level details
  155.    $ IPCRUNDEBUG=gory    myscript     # (Win32 only) prints data moving through
  156.                                       # the helper processes.
  157.  
  158. =back
  159.  
  160. We now return you to your regularly scheduled documentation.
  161.  
  162. =head2 Harnesses
  163.  
  164. Child processes and I/O handles are gathered in to a harness, then
  165. started and run until the processing is finished or aborted.
  166.  
  167. =head2 run() vs. start(); pump(); finish();
  168.  
  169. There are two modes you can run harnesses in: run() functions as an
  170. enhanced system(), and start()/pump()/finish() allow for background
  171. processes and scripted interactions with them.
  172.  
  173. When using run(), all data to be sent to the harness is set up in
  174. advance (though one can feed subprocesses input from subroutine refs to
  175. get around this limitation). The harness is run and all output is
  176. collected from it, then any child processes are waited for:
  177.  
  178.    run \@cmd, \<<IN, \$out;
  179.    blah
  180.    IN
  181.  
  182.    ## To precompile harnesses and run them later:
  183.    my $h = harness \@cmd, \<<IN, \$out;
  184.    blah
  185.    IN
  186.  
  187.    run $h;
  188.  
  189. The background and scripting API is provided by start(), pump(), and
  190. finish(): start() creates a harness if need be (by calling harness())
  191. and launches any subprocesses, pump() allows you to poll them for
  192. activity, and finish() then monitors the harnessed activities until they
  193. complete.
  194.  
  195.    ## Build the harness, open all pipes, and launch the subprocesses
  196.    my $h = start \@cat, \$in, \$out;
  197.    $in = "first input\n";
  198.  
  199.    ## Now do I/O.  start() does no I/O.
  200.    pump $h while length $in;  ## Wait for all input to go
  201.  
  202.    ## Now do some more I/O.
  203.    $in = "second input\n";
  204.    pump $h until $out =~ /second input/;
  205.  
  206.    ## Clean up
  207.    finish $h or die "cat returned $?";
  208.  
  209. You can optionally compile the harness with harness() prior to
  210. start()ing or run()ing, and you may omit start() between harness() and
  211. pump().  You might want to do these things if you compile your harnesses
  212. ahead of time.
  213.  
  214. =head2 Using regexps to match output
  215.  
  216. As shown in most of the scripting examples, the read-to-scalar facility
  217. for gathering subcommand's output is often used with regular expressions
  218. to detect stopping points.  This is because subcommand output often
  219. arrives in dribbles and drabs, often only a character or line at a time.
  220. This output is input for the main program and piles up in variables like
  221. the C<$out> and C<$err> in our examples.
  222.  
  223. Regular expressions can be used to wait for appropriate output in
  224. several ways.  The C<cat> example in the previous section demonstrates
  225. how to pump() until some string appears in the output.  Here's an
  226. example that uses C<smb> to fetch files from a remote server:
  227.  
  228.    $h = harness \@smbclient, \$in, \$out;
  229.  
  230.    $in = "cd /src\n";
  231.    $h->pump until $out =~ /^smb.*> \Z/m;
  232.    die "error cding to /src:\n$out" if $out =~ "ERR";
  233.    $out = '';
  234.  
  235.    $in = "mget *\n";
  236.    $h->pump until $out =~ /^smb.*> \Z/m;
  237.    die "error retrieving files:\n$out" if $out =~ "ERR";
  238.  
  239.    $in = "quit\n";
  240.    $h->finish;
  241.  
  242. Notice that we carefully clear $out after the first command/response
  243. cycle? That's because IPC::Run does not delete $out when we continue,
  244. and we don't want to trip over the old output in the second
  245. command/response cycle.
  246.  
  247. Say you want to accumulate all the output in $out and analyze it
  248. afterwards.  Perl offers incremental regular expression matching using
  249. the C<m//gc> and pattern matching idiom and the C<\G> assertion.
  250. IPC::Run is careful not to disturb the current C<pos()> value for
  251. scalars it appends data to, so we could modify the above so as not to
  252. destroy $out by adding a couple of C</gc> modifiers.  The C</g> keeps us
  253. from tripping over the previous prompt and the C</c> keeps us from
  254. resetting the prior match position if the expected prompt doesn't
  255. materialize immediately:
  256.  
  257.    $h = harness \@smbclient, \$in, \$out;
  258.  
  259.    $in = "cd /src\n";
  260.    $h->pump until $out =~ /^smb.*> \Z/mgc;
  261.    die "error cding to /src:\n$out" if $out =~ "ERR";
  262.  
  263.    $in = "mget *\n";
  264.    $h->pump until $out =~ /^smb.*> \Z/mgc;
  265.    die "error retrieving files:\n$out" if $out =~ "ERR";
  266.  
  267.    $in = "quit\n";
  268.    $h->finish;
  269.  
  270.    analyze( $out );
  271.  
  272. When using this technique, you may want to preallocate $out to have
  273. plenty of memory or you may find that the act of growing $out each time
  274. new input arrives causes an C<O(length($out)^2)> slowdown as $out grows.
  275. Say we expect no more than 10,000 characters of input at the most.  To
  276. preallocate memory to $out, do something like:
  277.  
  278.    my $out = "x" x 10_000;
  279.    $out = "";
  280.  
  281. C<perl> will allocate at least 10,000 characters' worth of space, then
  282. mark the $out as having 0 length without freeing all that yummy RAM.
  283.  
  284. =head2 Timeouts and Timers
  285.  
  286. More than likely, you don't want your subprocesses to run forever, and
  287. sometimes it's nice to know that they're going a little slowly.
  288. Timeouts throw exceptions after a some time has elapsed, timers merely
  289. cause pump() to return after some time has elapsed.  Neither is
  290. reset/restarted automatically.
  291.  
  292. Timeout objects are created by calling timeout( $interval ) and passing
  293. the result to run(), start() or harness().  The timeout period starts
  294. ticking just after all the child processes have been fork()ed or
  295. spawn()ed, and are polled for expiration in run(), pump() and finish().
  296. If/when they expire, an exception is thrown.  This is typically useful
  297. to keep a subprocess from taking too long.
  298.  
  299. If a timeout occurs in run(), all child processes will be terminated and
  300. all file/pipe/ptty descriptors opened by run() will be closed.  File
  301. descriptors opened by the parent process and passed in to run() are not
  302. closed in this event.
  303.  
  304. If a timeout occurs in pump(), pump_nb(), or finish(), it's up to you to
  305. decide whether to kill_kill() all the children or to implement some more
  306. graceful fallback.  No I/O will be closed in pump(), pump_nb() or
  307. finish() by such an exception (though I/O is often closed down in those
  308. routines during the natural course of events).
  309.  
  310. Often an exception is too harsh.  timer( $interval ) creates timer
  311. objects that merely prevent pump() from blocking forever.  This can be
  312. useful for detecting stalled I/O or printing a soothing message or "."
  313. to pacify an anxious user.
  314.  
  315. Timeouts and timers can both be restarted at any time using the timer's
  316. start() method (this is not the start() that launches subprocesses).  To
  317. restart a timer, you need to keep a reference to the timer:
  318.  
  319.    ## Start with a nice long timeout to let smbclient connect.  If
  320.    ## pump or finish take too long, an exception will be thrown.
  321.  
  322.  my $h;
  323.  eval {
  324.    $h = harness \@smbclient, \$in, \$out, \$err, ( my $t = timeout 30 );
  325.    sleep 11;  # No effect: timer not running yet
  326.  
  327.    start $h;
  328.    $in = "cd /src\n";
  329.    pump $h until ! length $in;
  330.  
  331.    $in = "ls\n";
  332.    ## Now use a short timeout, since this should be faster
  333.    $t->start( 5 );
  334.    pump $h until ! length $in;
  335.  
  336.    $t->start( 10 );  ## Give smbclient a little while to shut down.
  337.    $h->finish;
  338.  };
  339.  if ( $@ ) {
  340.    my $x = $@;    ## Preserve $@ in case another exception occurs
  341.    $h->kill_kill; ## kill it gently, then brutally if need be, or just
  342.                    ## brutally on Win32.
  343.    die $x;
  344.  }
  345.  
  346. Timeouts and timers are I<not> checked once the subprocesses are shut
  347. down; they will not expire in the interval between the last valid
  348. process and when IPC::Run scoops up the processes' result codes, for
  349. instance.
  350.  
  351. =head2 Spawning synchronization, child exception propagation
  352.  
  353. start() pauses the parent until the child executes the command or CODE
  354. reference and propagates any exceptions thrown (including exec()
  355. failure) back to the parent.  This has several pleasant effects: any
  356. exceptions thrown in the child, including exec() failure, come flying
  357. out of start() or run() as though they had ocurred in the parent.
  358.  
  359. This includes exceptions your code thrown from init subs.  In this
  360. example:
  361.  
  362.    eval {
  363.       run \@cmd, init => sub { die "blast it! foiled again!" };
  364.    };
  365.    print $@;
  366.  
  367. the exception "blast it! foiled again" will be thrown from the child
  368. process (preventing the exec()) and printed by the parent.
  369.  
  370. In situations like
  371.  
  372.    run \@cmd1, "|", \@cmd2, "|", \@cmd3;
  373.  
  374. @cmd1 will be initted and exec()ed before @cmd2, and @cmd2 before @cmd3.
  375. This can save time and prevent oddball errors emitted by later commands
  376. when earlier commands fail to execute.  Note that IPC::Run doesn't start
  377. any commands unless it can find the executables referenced by all
  378. commands.  These executables must pass both the C<-f> and C<-x> tests
  379. described in L<perlfunc>.
  380.  
  381. Another nice effect is that init() subs can take their time doing things
  382. and there will be no problems caused by a parent continuing to execute
  383. before a child's init() routine is complete.  Say the init() routine
  384. needs to open a socket or a temp file that the parent wants to connect
  385. to; without this synchronization, the parent will need to implement a
  386. retry loop to wait for the child to run, since often, the parent gets a
  387. lot of things done before the child's first timeslice is allocated.
  388.  
  389. This is also quite necessary for pseudo-tty initialization, which needs
  390. to take place before the parent writes to the child via pty.  Writes
  391. that occur before the pty is set up can get lost.
  392.  
  393. A final, minor, nicety is that debugging output from the child will be
  394. emitted before the parent continues on, making for much clearer debugging
  395. output in complex situations.
  396.  
  397. The only drawback I can conceive of is that the parent can't continue to
  398. operate while the child is being initted.  If this ever becomes a
  399. problem in the field, we can implement an option to avoid this behavior,
  400. but I don't expect it to.
  401.  
  402. B<Win32>: executing CODE references isn't supported on Win32, see
  403. L</Win32 LIMITATIONS> for details.
  404.  
  405. =head2 Syntax
  406.  
  407. run(), start(), and harness() can all take a harness specification
  408. as input.  A harness specification is either a single string to be passed
  409. to the systems' shell:
  410.  
  411.    run "echo 'hi there'";
  412.  
  413. or a list of commands, io operations, and/or timers/timeouts to execute.
  414. Consecutive commands must be separated by a pipe operator '|' or an '&'.
  415. External commands are passed in as array references, and, on systems
  416. supporting fork(), Perl code may be passed in as subs:
  417.  
  418.    run \@cmd;
  419.    run \@cmd1, '|', \@cmd2;
  420.    run \@cmd1, '&', \@cmd2;
  421.    run \&sub1;
  422.    run \&sub1, '|', \&sub2;
  423.    run \&sub1, '&', \&sub2;
  424.  
  425. '|' pipes the stdout of \@cmd1 the stdin of \@cmd2, just like a
  426. shell pipe.  '&' does not.  Child processes to the right of a '&'
  427. will have their stdin closed unless it's redirected-to.
  428.  
  429. L<IPC::Run::IO> objects may be passed in as well, whether or not
  430. child processes are also specified:
  431.  
  432.    run io( "infile", ">", \$in ), io( "outfile", "<", \$in );
  433.       
  434. as can L<IPC::Run::Timer> objects:
  435.  
  436.    run \@cmd, io( "outfile", "<", \$in ), timeout( 10 );
  437.  
  438. Commands may be followed by scalar, sub, or i/o handle references for
  439. redirecting
  440. child process input & output:
  441.  
  442.    run \@cmd,  \undef,            \$out;
  443.    run \@cmd,  \$in,              \$out;
  444.    run \@cmd1, \&in, '|', \@cmd2, \*OUT;
  445.    run \@cmd1, \*IN, '|', \@cmd2, \&out;
  446.  
  447. This is known as succinct redirection syntax, since run(), start()
  448. and harness(), figure out which file descriptor to redirect and how.
  449. File descriptor 0 is presumed to be an input for
  450. the child process, all others are outputs.  The assumed file
  451. descriptor always starts at 0, unless the command is being piped to,
  452. in which case it starts at 1.
  453.  
  454. To be explicit about your redirects, or if you need to do more complex
  455. things, there's also a redirection operator syntax:
  456.  
  457.    run \@cmd, '<', \undef, '>',  \$out;
  458.    run \@cmd, '<', \undef, '>&', \$out_and_err;
  459.    run(
  460.       \@cmd1,
  461.          '<', \$in,
  462.       '|', \@cmd2,
  463.          \$out
  464.    );
  465.  
  466. Operator syntax is required if you need to do something other than simple
  467. redirection to/from scalars or subs, like duping or closing file descriptors
  468. or redirecting to/from a named file.  The operators are covered in detail
  469. below.
  470.  
  471. After each \@cmd (or \&foo), parsing begins in succinct mode and toggles to
  472. operator syntax mode when an operator (ie plain scalar, not a ref) is seen.
  473. Once in
  474. operator syntax mode, parsing only reverts to succinct mode when a '|' or
  475. '&' is seen.
  476.  
  477. In succinct mode, each parameter after the \@cmd specifies what to
  478. do with the next highest file descriptor. These File descriptor start
  479. with 0 (stdin) unless stdin is being piped to (C<'|', \@cmd>), in which
  480. case they start with 1 (stdout).  Currently, being on the left of
  481. a pipe (C<\@cmd, \$out, \$err, '|'>) does I<not> cause stdout to be
  482. skipped, though this may change since it's not as DWIMerly as it
  483. could be.  Only stdin is assumed to be an
  484. input in succinct mode, all others are assumed to be outputs.
  485.  
  486. If no piping or redirection is specified for a child, it will inherit
  487. the parent's open file handles as dictated by your system's
  488. close-on-exec behavior and the $^F flag, except that processes after a
  489. '&' will not inherit the parent's stdin. Also note that $^F does not
  490. affect file desciptors obtained via POSIX, since it only applies to
  491. full-fledged Perl file handles.  Such processes will have their stdin
  492. closed unless it has been redirected-to.
  493.  
  494. If you want to close a child processes stdin, you may do any of:
  495.  
  496.    run \@cmd, \undef;
  497.    run \@cmd, \"";
  498.    run \@cmd, '<&-';
  499.    run \@cmd, '0<&-';
  500.  
  501. Redirection is done by placing redirection specifications immediately 
  502. after a command or child subroutine:
  503.  
  504.    run \@cmd1,      \$in, '|', \@cmd2,      \$out;
  505.    run \@cmd1, '<', \$in, '|', \@cmd2, '>', \$out;
  506.  
  507. If you omit the redirection operators, descriptors are counted
  508. starting at 0.  Descriptor 0 is assumed to be input, all others
  509. are outputs.  A leading '|' consumes descriptor 0, so this
  510. works as expected.
  511.  
  512.    run \@cmd1, \$in, '|', \@cmd2, \$out;
  513.    
  514. The parameter following a redirection operator can be a scalar ref,
  515. a subroutine ref, a file name, an open filehandle, or a closed
  516. filehandle.
  517.  
  518. If it's a scalar ref, the child reads input from or sends output to
  519. that variable:
  520.  
  521.    $in = "Hello World.\n";
  522.    run \@cat, \$in, \$out;
  523.    print $out;
  524.  
  525. Scalars used in incremental (start()/pump()/finish()) applications are treated
  526. as queues: input is removed from input scalers, resulting in them dwindling
  527. to '', and output is appended to output scalars.  This is not true of 
  528. harnesses run() in batch mode.
  529.  
  530. It's usually wise to append new input to be sent to the child to the input
  531. queue, and you'll often want to zap output queues to '' before pumping.
  532.  
  533.    $h = start \@cat, \$in;
  534.    $in = "line 1\n";
  535.    pump $h;
  536.    $in .= "line 2\n";
  537.    pump $h;
  538.    $in .= "line 3\n";
  539.    finish $h;
  540.  
  541. The final call to finish() must be there: it allows the child process(es)
  542. to run to completion and waits for their exit values.
  543.  
  544. =head1 OBSTINATE CHILDREN
  545.  
  546. Interactive applications are usually optimized for human use.  This
  547. can help or hinder trying to interact with them through modules like
  548. IPC::Run.  Frequently, programs alter their behavior when they detect
  549. that stdin, stdout, or stderr are not connected to a tty, assuming that
  550. they are being run in batch mode.  Whether this helps or hurts depends
  551. on which optimizations change.  And there's often no way of telling
  552. what a program does in these areas other than trial and error and,
  553. occasionally, reading the source.  This includes different versions
  554. and implementations of the same program.
  555.  
  556. All hope is not lost, however.  Most programs behave in reasonably
  557. tractable manners, once you figure out what it's trying to do.
  558.  
  559. Here are some of the issues you might need to be aware of.
  560.  
  561. =over
  562.  
  563. =item *
  564.  
  565. fflush()ing stdout and stderr
  566.  
  567. This lets the user see stdout and stderr immediately.  Many programs
  568. undo this optimization if stdout is not a tty, making them harder to
  569. manage by things like IPC::Run.
  570.  
  571. Many programs decline to fflush stdout or stderr if they do not
  572. detect a tty there.  Some ftp commands do this, for instance.
  573.  
  574. If this happens to you, look for a way to force interactive behavior,
  575. like a command line switch or command.  If you can't, you will
  576. need to use a pseudo terminal ('<pty<' and '>pty>').
  577.  
  578. =item *
  579.  
  580. false prompts
  581.  
  582. Interactive programs generally do not guarantee that output from user
  583. commands won't contain a prompt string.  For example, your shell prompt
  584. might be a '$', and a file named '$' might be the only file in a directory
  585. listing.
  586.  
  587. This can make it hard to guarantee that your output parser won't be fooled
  588. into early termination of results.
  589.  
  590. To help work around this, you can see if the program can alter it's 
  591. prompt, and use something you feel is never going to occur in actual
  592. practice.
  593.  
  594. You should also look for your prompt to be the only thing on a line:
  595.  
  596.    pump $h until $out =~ /^<SILLYPROMPT>\s?\z/m;
  597.  
  598. (use C<(?!\n)\Z> in place of C<\z> on older perls).
  599.  
  600. You can also take the approach that IPC::ChildSafe takes and emit a
  601. command with known output after each 'real' command you issue, then
  602. look for this known output.  See new_appender() and new_chunker() for
  603. filters that can help with this task.
  604.  
  605. If it's not convenient or possibly to alter a prompt or use a known
  606. command/response pair, you might need to autodetect the prompt in case
  607. the local version of the child program is different then the one
  608. you tested with, or if the user has control over the look & feel of
  609. the prompt.
  610.  
  611. =item *
  612.  
  613. Refusing to accept input unless stdin is a tty.
  614.  
  615. Some programs, for security reasons, will only accept certain types
  616. of input from a tty.  su, notable, will not prompt for a password unless
  617. it's connected to a tty.
  618.  
  619. If this is your situation, use a pseudo terminal ('<pty<' and '>pty>').
  620.  
  621. =item *
  622.  
  623. Not prompting unless connected to a tty.
  624.  
  625. Some programs don't prompt unless stdin or stdout is a tty.  See if you can
  626. turn prompting back on.  If not, see if you can come up with a command that
  627. you can issue after every real command and look for it's output, as
  628. IPC::ChildSafe does.   There are two filters included with IPC::Run that
  629. can help with doing this: appender and chunker (see new_appender() and
  630. new_chunker()).
  631.  
  632. =item *
  633.  
  634. Different output format when not connected to a tty.
  635.  
  636. Some commands alter their formats to ease machine parsability when they
  637. aren't connected to a pipe.  This is actually good, but can be surprising.
  638.  
  639. =back
  640.  
  641. =head1 PSEUDO TERMINALS
  642.  
  643. On systems providing pseudo terminals under /dev, IPC::Run can use IO::Pty
  644. (available on CPAN) to provide a terminal environment to subprocesses.
  645. This is necessary when the subprocess really wants to think it's connected
  646. to a real terminal.
  647.  
  648. =head2 CAVEATS
  649.  
  650. Psuedo-terminals are not pipes, though they are similar.  Here are some
  651. differences to watch out for.
  652.  
  653. =over
  654.  
  655. =item Echoing
  656.  
  657. Sending to stdin will cause an echo on stdout, which occurs before each
  658. line is passed to the child program.  There is currently no way to
  659. disable this, although the child process can and should disable it for
  660. things like passwords.
  661.  
  662. =item Shutdown
  663.  
  664. IPC::Run cannot close a pty until all output has been collected.  This
  665. means that it is not possible to send an EOF to stdin by half-closing
  666. the pty, as we can when using a pipe to stdin.
  667.  
  668. This means that you need to send the child process an exit command or
  669. signal, or run() / finish() will time out.  Be careful not to expect a
  670. prompt after sending the exit command.
  671.  
  672. =item Command line editing
  673.  
  674. Some subprocesses, notable shells that depend on the user's prompt
  675. settings, will reissue the prompt plus the command line input so far
  676. once for each character.
  677.  
  678. =item '>pty>' means '&>pty>', not '1>pty>'
  679.  
  680. The pseudo terminal redirects both stdout and stderr unless you specify
  681. a file descriptor.  If you want to grab stderr separately, do this:
  682.  
  683.    start \@cmd, '<pty<', \$in, '>pty>', \$out, '2>', \$err;
  684.  
  685. =item stdin, stdout, and stderr not inherited
  686.  
  687. Child processes harnessed to a pseudo terminal have their stdin, stdout,
  688. and stderr completely closed before any redirection operators take
  689. effect.  This casts of the bonds of the controlling terminal.  This is
  690. not done when using pipes.
  691.  
  692. Right now, this affects all children in a harness that has a pty in use,
  693. even if that pty would not affect a particular child.  That's a bug and
  694. will be fixed.  Until it is, it's best not to mix-and-match children.
  695.  
  696. =back
  697.  
  698. =head2 Redirection Operators
  699.  
  700.    Operator       SHNP   Description
  701.    ========       ====   ===========
  702.    <, N<          SHN    Redirects input to a child's fd N (0 assumed)
  703.  
  704.    >, N>          SHN    Redirects output from a child's fd N (1 assumed)
  705.    >>, N>>        SHN    Like '>', but appends to scalars or named files
  706.    >&, &>         SHN    Redirects stdout & stderr from a child process
  707.  
  708.    <pty, N<pty    S      Like '<', but uses a pseudo-tty instead of a pipe
  709.    >pty, N>pty    S      Like '>', but uses a pseudo-tty instead of a pipe
  710.  
  711.    N<&M                  Dups input fd N to input fd M
  712.    M>&N                  Dups output fd N to input fd M
  713.    N<&-                  Closes fd N
  714.  
  715.    <pipe, N<pipe     P   Pipe opens H for caller to read, write, close.
  716.    >pipe, N>pipe     P   Pipe opens H for caller to read, write, close.
  717.                       
  718. 'N' and 'M' are placeholders for integer file descriptor numbers.  The
  719. terms 'input' and 'output' are from the child process's perspective.
  720.  
  721. The SHNP field indicates what parameters an operator can take:
  722.  
  723.    S: \$scalar or \&function references.  Filters may be used with
  724.       these operators (and only these).
  725.    H: \*HANDLE or IO::Handle for caller to open, and close
  726.    N: "file name".
  727.    P: \*HANDLE opened by IPC::Run as the parent end of a pipe, but read
  728.       and written to and closed by the caller (like IPC::Open3).
  729.  
  730. =over
  731.  
  732. =item Redirecting input: [n]<, [n]<pipe
  733.  
  734. You can input the child reads on file descriptor number n to come from a
  735. scalar variable, subroutine, file handle, or a named file.  If stdin
  736. is not redirected, the parent's stdin is inherited.
  737.  
  738.    run \@cat, \undef          ## Closes child's stdin immediately
  739.       or die "cat returned $?"; 
  740.  
  741.    run \@cat, \$in;
  742.  
  743.    run \@cat, \<<TOHERE;
  744.    blah
  745.    TOHERE
  746.  
  747.    run \@cat, \&input;       ## Calls &input, feeding data returned
  748.                               ## to child's.  Closes child's stdin
  749.                               ## when undef is returned.
  750.  
  751. Redirecting from named files requires you to use the input
  752. redirection operator:
  753.  
  754.    run \@cat, '<.profile';
  755.    run \@cat, '<', '.profile';
  756.  
  757.    open IN, "<foo";
  758.    run \@cat, \*IN;
  759.    run \@cat, *IN{IO};
  760.  
  761. The form used second example here is the safest,
  762. since filenames like "0" and "&more\n" won't confuse &run:
  763.  
  764. You can't do either of
  765.  
  766.    run \@a, *IN;      ## INVALID
  767.    run \@a, '<', *IN; ## BUGGY: Reads file named like "*main::A"
  768.    
  769. because perl passes a scalar containing a string that
  770. looks like "*main::A" to &run, and &run can't tell the difference
  771. between that and a redirection operator or a file name.  &run guarantees
  772. that any scalar you pass after a redirection operator is a file name.
  773.  
  774. If your child process will take input from file descriptors other
  775. than 0 (stdin), you can use a redirection operator with any of the
  776. valid input forms (scalar ref, sub ref, etc.):
  777.  
  778.    run \@cat, '3<', \$in3;
  779.  
  780. When redirecting input from a scalar ref, the scalar ref is
  781. used as a queue.  This allows you to use &harness and pump() to
  782. feed incremental bits of input to a coprocess.  See L</Coprocesses>
  783. below for more information.
  784.  
  785. The <pipe operator opens the write half of a pipe on the filehandle
  786. glob reference it takes as an argument:
  787.  
  788.    $h = start \@cat, '<pipe', \*IN;
  789.    print IN "hello world\n";
  790.    pump $h;
  791.    close IN;
  792.    finish $h;
  793.  
  794. Unlike the other '<' operators, IPC::Run does nothing further with
  795. it: you are responsible for it.  The previous example is functionally
  796. equivalent to:
  797.  
  798.    pipe( \*R, \*IN ) or die $!;
  799.    $h = start \@cat, '<', \*IN;
  800.    print IN "hello world\n";
  801.    pump $h;
  802.    close IN;
  803.    finish $h;
  804.  
  805. This is like the behavior of IPC::Open2 and IPC::Open3.
  806.  
  807. B<Win32>: The handle returned is actually a socket handle, so you can
  808. use select() on it.
  809.  
  810. =item Redirecting output: [n]>, [n]>>, [n]>&[m], [n]>pipe
  811.  
  812. You can redirect any output the child emits
  813. to a scalar variable, subroutine, file handle, or file name.  You
  814. can have &run truncate or append to named files or scalars.  If
  815. you are redirecting stdin as well, or if the command is on the
  816. receiving end of a pipeline ('|'), you can omit the redirection
  817. operator:
  818.  
  819.    @ls = ( 'ls' );
  820.    run \@ls, \undef, \$out
  821.       or die "ls returned $?"; 
  822.  
  823.    run \@ls, \undef, \&out;  ## Calls &out each time some output
  824.                               ## is received from the child's 
  825.                               ## when undef is returned.
  826.  
  827.    run \@ls, \undef, '2>ls.err';
  828.    run \@ls, '2>', 'ls.err';
  829.  
  830. The two parameter form guarantees that the filename
  831. will not be interpreted as a redirection operator:
  832.  
  833.    run \@ls, '>', "&more";
  834.    run \@ls, '2>', ">foo\n";
  835.  
  836. You can pass file handles you've opened for writing:
  837.  
  838.    open( *OUT, ">out.txt" );
  839.    open( *ERR, ">err.txt" );
  840.    run \@cat, \*OUT, \*ERR;
  841.  
  842. Passing a scalar reference and a code reference requires a little
  843. more work, but allows you to capture all of the output in a scalar
  844. or each piece of output by a callback:
  845.  
  846. These two do the same things:
  847.  
  848.    run( [ 'ls' ], '2>', sub { $err_out .= $_[0] } );
  849.  
  850. does the same basic thing as:
  851.  
  852.    run( [ 'ls' ], '2>', \$err_out );
  853.  
  854. The subroutine will be called each time some data is read from the child.
  855.  
  856. The >pipe operator is different in concept than the other '>' operators,
  857. although it's syntax is similar:
  858.  
  859.    $h = start \@cat, $in, '>pipe', \*OUT, '2>pipe', \*ERR;
  860.    $in = "hello world\n";
  861.    finish $h;
  862.    print <OUT>;
  863.    print <ERR>;
  864.    close OUT;
  865.    close ERR;
  866.  
  867. causes two pipe to be created, with one end attached to cat's stdout
  868. and stderr, respectively, and the other left open on OUT and ERR, so
  869. that the script can manually
  870. read(), select(), etc. on them.  This is like
  871. the behavior of IPC::Open2 and IPC::Open3.
  872.  
  873. B<Win32>: The handle returned is actually a socket handle, so you can
  874. use select() on it.
  875.  
  876. =item Duplicating output descriptors: >&m, n>&m
  877.  
  878. This duplicates output descriptor number n (default is 1 if n is omitted)
  879. from descriptor number m.
  880.  
  881. =item Duplicating input descriptors: <&m, n<&m
  882.  
  883. This duplicates input descriptor number n (default is 0 if n is omitted)
  884. from descriptor number m
  885.  
  886. =item Closing descriptors: <&-, 3<&-
  887.  
  888. This closes descriptor number n (default is 0 if n is omitted).  The
  889. following commands are equivalent:
  890.  
  891.    run \@cmd, \undef;
  892.    run \@cmd, '<&-';
  893.    run \@cmd, '<in.txt', '<&-';
  894.  
  895. Doing
  896.  
  897.    run \@cmd, \$in, '<&-';    ## SIGPIPE recipe.
  898.  
  899. is dangerous: the parent will get a SIGPIPE if $in is not empty.
  900.  
  901. =item Redirecting both stdout and stderr: &>, >&, &>pipe, >pipe&
  902.  
  903. The following pairs of commands are equivalent:
  904.  
  905.    run \@cmd, '>&', \$out;       run \@cmd, '>', \$out,     '2>&1';
  906.    run \@cmd, '>&', 'out.txt';   run \@cmd, '>', 'out.txt', '2>&1';
  907.  
  908. etc.
  909.  
  910. File descriptor numbers are not permitted to the left or the right of
  911. these operators, and the '&' may occur on either end of the operator.
  912.  
  913. The '&>pipe' and '>pipe&' variants behave like the '>pipe' operator, except
  914. that both stdout and stderr write to the created pipe.
  915.  
  916. =item Redirection Filters
  917.  
  918. Both input redirections and output redirections that use scalars or
  919. subs as endpoints may have an arbitrary number of filter subs placed
  920. between them and the child process.  This is useful if you want to
  921. receive output in chunks, or if you want to massage each chunk of
  922. data sent to the child.  To use this feature, you must use operator
  923. syntax:
  924.  
  925.    run(
  926.       \@cmd
  927.          '<', \&in_filter_2, \&in_filter_1, $in,
  928.          '>', \&out_filter_1, \&in_filter_2, $out,
  929.    );
  930.  
  931. This capability is not provided for IO handles or named files.
  932.  
  933. Two filters are provided by IPC::Run: appender and chunker.  Because
  934. these may take an argument, you need to use the constructor functions
  935. new_appender() and new_chunker() rather than using \& syntax:
  936.  
  937.    run(
  938.       \@cmd
  939.          '<', new_appender( "\n" ), $in,
  940.          '>', new_chunker, $out,
  941.    );
  942.  
  943. =back
  944.  
  945. =head2 Just doing I/O
  946.  
  947. If you just want to do I/O to a handle or file you open yourself, you
  948. may specify a filehandle or filename instead of a command in the harness
  949. specification:
  950.  
  951.    run io( "filename", '>', \$recv );
  952.  
  953.    $h = start io( $io, '>', \$recv );
  954.  
  955.    $h = harness \@cmd, '&', io( "file", '<', \$send );
  956.  
  957. =head2 Options
  958.  
  959. Options are passed in as name/value pairs:
  960.  
  961.    run \@cat, \$in, debug => 1;
  962.  
  963. If you pass the debug option, you may want to pass it in first, so you
  964. can see what parsing is going on:
  965.  
  966.    run debug => 1, \@cat, \$in;
  967.  
  968. =over
  969.  
  970. =item debug
  971.  
  972. Enables debugging output in parent and child.  Debugging info is emitted
  973. to the STDERR that was present when IPC::Run was first C<use()>ed (it's
  974. C<dup()>ed out of the way so that it can be redirected in children without
  975. having debugging output emitted on it).
  976.  
  977. =back
  978.  
  979. =head1 RETURN VALUES
  980.  
  981. harness() and start() return a reference to an IPC::Run harness.  This is
  982. blessed in to the IPC::Run package, so you may make later calls to
  983. functions as members if you like:
  984.  
  985.    $h = harness( ... );
  986.    $h->start;
  987.    $h->pump;
  988.    $h->finish;
  989.  
  990.    $h = start( .... );
  991.    $h->pump;
  992.    ...
  993.  
  994. Of course, using method call syntax lets you deal with any IPC::Run
  995. subclasses that might crop up, but don't hold your breath waiting for
  996. any.
  997.  
  998. run() and finish() return TRUE when all subcommands exit with a 0 result
  999. code.  B<This is the opposite of perl's system() command>.
  1000.  
  1001. All routines raise exceptions (via die()) when error conditions are
  1002. recognized.  A non-zero command result is not treated as an error
  1003. condition, since some commands are tests whose results are reported 
  1004. in their exit codes.
  1005.  
  1006. =head1 ROUTINES
  1007.  
  1008. =over
  1009.  
  1010. =cut
  1011.  
  1012. use strict;
  1013. use Exporter ();
  1014. use vars qw{$VERSION @ISA @FILTER_IMP @FILTERS @API @EXPORT_OK %EXPORT_TAGS};
  1015. BEGIN {
  1016.     $VERSION = '0.89';
  1017.     @ISA     = qw{ Exporter };
  1018.  
  1019.     ## We use @EXPORT for the end user's convenience: there's only one function
  1020.     ## exported, it's homonymous with the module, it's an unusual name, and
  1021.     ## it can be suppressed by "use IPC::Run ();".
  1022.     @FILTER_IMP = qw( input_avail get_more_input );
  1023.     @FILTERS    = qw(
  1024.         new_appender
  1025.         new_chunker
  1026.         new_string_source
  1027.         new_string_sink
  1028.     );
  1029.     @API        = qw(
  1030.         run
  1031.         harness start pump pumpable finish
  1032.         signal kill_kill reap_nb
  1033.         io timer timeout
  1034.         close_terminal
  1035.         binary
  1036.     );
  1037.     @EXPORT_OK = ( @API, @FILTER_IMP, @FILTERS, qw( Win32_MODE ) );
  1038.     %EXPORT_TAGS = (
  1039.         'filter_imp' => \@FILTER_IMP,
  1040.         'all'        => \@EXPORT_OK,
  1041.         'filters'    => \@FILTERS,
  1042.         'api'        => \@API,
  1043.     );
  1044.  
  1045. }
  1046.  
  1047. use strict;
  1048. use IPC::Run::Debug;
  1049. use Exporter;
  1050. use Fcntl;
  1051. use POSIX ();
  1052. use Symbol;
  1053. use Carp;
  1054. use File::Spec ();
  1055. use IO::Handle;
  1056. require IPC::Run::IO;
  1057. require IPC::Run::Timer;
  1058. use UNIVERSAL ();
  1059.  
  1060. use constant Win32_MODE => $^O =~ /os2|Win32/i;
  1061.  
  1062. BEGIN {
  1063.    if ( Win32_MODE ) {
  1064.       eval "use IPC::Run::Win32Helper; 1;"
  1065.          or ( $@ && die ) or die "$!";
  1066.    }
  1067.    else {
  1068.       eval "use File::Basename; 1;" or die $!;
  1069.    }
  1070. }
  1071.  
  1072. sub input_avail();
  1073. sub get_more_input();
  1074.  
  1075. ###############################################################################
  1076.  
  1077. ##
  1078. ## State machine states, set in $self->{STATE}
  1079. ##
  1080. ## These must be in ascending order numerically
  1081. ##
  1082. sub _newed()    {0}
  1083. sub _harnessed(){1}
  1084. sub _finished() {2}   ## _finished behave almost exactly like _harnessed
  1085. sub _started()  {3}
  1086.  
  1087. ##
  1088. ## Which fds have been opened in the parent.  This may have extra fds, since
  1089. ## we aren't all that rigorous about closing these off, but that's ok.  This
  1090. ## is used on Unixish OSs to close all fds in the child that aren't needed
  1091. ## by that particular child.
  1092. my %fds;
  1093.  
  1094. ## There's a bit of hackery going on here.
  1095. ##
  1096. ## We want to have any code anywhere be able to emit
  1097. ## debugging statements without knowing what harness the code is
  1098. ## being called in/from, since we'd need to pass a harness around to
  1099. ## everything.
  1100. ##
  1101. ## Thus, $cur_self was born.
  1102.  
  1103. use vars qw( $cur_self );
  1104.  
  1105. sub _debug_fd {
  1106.    return fileno STDERR unless defined $cur_self;
  1107.  
  1108.    if ( _debugging && ! defined $cur_self->{DEBUG_FD} ) {
  1109.       my $fd = select STDERR; $| = 1; select $fd;
  1110.       $cur_self->{DEBUG_FD} = POSIX::dup fileno STDERR;
  1111.       _debug( "debugging fd is $cur_self->{DEBUG_FD}\n" )
  1112.          if _debugging_details;
  1113.    }
  1114.  
  1115.    return fileno STDERR unless defined $cur_self->{DEBUG_FD};
  1116.  
  1117.    return $cur_self->{DEBUG_FD}
  1118. }
  1119.  
  1120. sub DESTROY {
  1121.    ## We absolutely do not want to do anything else here.  We are likely
  1122.    ## to be in a child process and we don't want to do things like kill_kill
  1123.    ## ourself or cause other destruction.
  1124.    my IPC::Run $self = shift;
  1125.    POSIX::close $self->{DEBUG_FD} if defined $self->{DEBUG_FD};
  1126.    $self->{DEBUG_FD} = undef;
  1127. }
  1128.  
  1129. ##
  1130. ## Support routines (NOT METHODS)
  1131. ##
  1132. my %cmd_cache;
  1133.  
  1134. sub _search_path {
  1135.    my ( $cmd_name ) = @_;
  1136.    if ( File::Spec->file_name_is_absolute( $cmd_name ) && -x $cmd_name) {
  1137.       _debug "'", $cmd_name, "' is absolute"
  1138.          if _debugging_details;
  1139.       return $cmd_name;
  1140.    }
  1141.  
  1142.    my $dirsep =
  1143.       ( Win32_MODE
  1144.          ? '[/\\\\]'
  1145.       : $^O =~ /MacOS/
  1146.          ? ':'
  1147.       : $^O =~ /VMS/
  1148.          ? '[\[\]]'
  1149.       : '/'
  1150.       );
  1151.  
  1152.    if ( Win32_MODE
  1153.       && ( $cmd_name =~ /$dirsep/ )
  1154. #      && ( $cmd_name !~ /\..+$/ )  ## Only run if cmd_name has no extension?
  1155.       && ( $cmd_name !~ m!\.[^\\/\.]+$! )
  1156.     ) {
  1157.  
  1158.       _debug "no extension(.exe), checking ENV{PATHEXT}"  if _debugging;
  1159.       for ( split /;/, $ENV{PATHEXT} || ".COM;.BAT;.EXE" ) {
  1160.          my $name = "$cmd_name$_";
  1161.          $cmd_name = $name, last if -f $name && -x _;
  1162.       }
  1163.       _debug "cmd_name is now '$cmd_name'"  if _debugging;
  1164.    }
  1165.  
  1166.    if ( $cmd_name =~ /($dirsep)/ ) {
  1167.       _debug "'$cmd_name' contains '$1'"  if _debugging;
  1168.       croak "file not found: $cmd_name"    unless -e $cmd_name;
  1169.       croak "not a file: $cmd_name"        unless -f $cmd_name;
  1170.       croak "permission denied: $cmd_name" unless -x $cmd_name;
  1171.       return $cmd_name;
  1172.    }
  1173.  
  1174.    if ( exists $cmd_cache{$cmd_name} ) {
  1175.       _debug "'$cmd_name' found in cache: '$cmd_cache{$cmd_name}'"
  1176.          if _debugging;
  1177.       return $cmd_cache{$cmd_name} if -x $cmd_cache{$cmd_name};
  1178.       _debug "'$cmd_cache{$cmd_name}' no longer executable, searching..."
  1179.          if _debugging;
  1180.       delete $cmd_cache{$cmd_name};
  1181.    }
  1182.  
  1183.    my @searched_in;
  1184.  
  1185.    ## This next bit is Unix/Win32 specific, unfortunately.
  1186.    ## There's been some conversation about extending File::Spec to provide
  1187.    ## a universal interface to PATH, but I haven't seen it yet.
  1188.       my $re = Win32_MODE ? qr/;/ : qr/:/;
  1189.  
  1190. LOOP:
  1191.    for ( split( $re, $ENV{PATH}, -1 ) ) {
  1192.       $_ = "." unless length $_;
  1193.       push @searched_in, $_;
  1194.  
  1195.       my $prospect = File::Spec->catfile( $_, $cmd_name );
  1196.       my @prospects;
  1197.  
  1198.       @prospects =
  1199.          ( Win32_MODE && ! ( -f $prospect && -x _ ) )
  1200.             ? map "$prospect$_", split /;/, $ENV{PATHEXT} || ".COM;.BAT;.EXE"
  1201.             : ( $prospect );
  1202.  
  1203.       for my $found ( @prospects ) {
  1204.          if ( -f $found && -x _ ) {
  1205.             $cmd_cache{$cmd_name} = $found;
  1206.             last LOOP;
  1207.          }
  1208.       }
  1209.    }
  1210.  
  1211.    if ( exists $cmd_cache{$cmd_name} ) {
  1212.       _debug "'", $cmd_name, "' added to cache: '", $cmd_cache{$cmd_name}, "'"
  1213.          if _debugging_details;
  1214.       return $cmd_cache{$cmd_name};
  1215.    }
  1216.  
  1217.    croak "Command '$cmd_name' not found in " . join( ", ", @searched_in );
  1218. }
  1219.  
  1220.  
  1221. sub _empty($) { ! ( defined $_[0] && length $_[0] ) }
  1222.  
  1223. ## 'safe' versions of otherwise fun things to do. See also IPC::Run::Win32Helper.
  1224. sub _close {
  1225.    confess 'undef' unless defined $_[0];
  1226.    no strict 'refs';
  1227.    my $fd = $_[0] =~ /^\d+$/ ? $_[0] : fileno $_[0];
  1228.    my $r = POSIX::close $fd;
  1229.    $r = $r ? '' : " ERROR $!";
  1230.    delete $fds{$fd};
  1231.    _debug "close( $fd ) = " . ( $r || 0 ) if _debugging_details;
  1232. }
  1233.  
  1234. sub _dup {
  1235.    confess 'undef' unless defined $_[0];
  1236.    my $r = POSIX::dup( $_[0] );
  1237.    croak "$!: dup( $_[0] )" unless defined $r;
  1238.    $r = 0 if $r eq '0 but true';
  1239.    _debug "dup( $_[0] ) = $r" if _debugging_details;
  1240.    $fds{$r} = 1;
  1241.    return $r;
  1242. }
  1243.  
  1244.  
  1245. sub _dup2_rudely {
  1246.    confess 'undef' unless defined $_[0] && defined $_[1];
  1247.    my $r = POSIX::dup2( $_[0], $_[1] );
  1248.    croak "$!: dup2( $_[0], $_[1] )" unless defined $r;
  1249.    $r = 0 if $r eq '0 but true';
  1250.    _debug "dup2( $_[0], $_[1] ) = $r" if _debugging_details;
  1251.    $fds{$r} = 1;
  1252.    return $r;
  1253. }
  1254.  
  1255. sub _exec {
  1256.    confess 'undef passed' if grep !defined, @_;
  1257. #   exec @_ or croak "$!: exec( " . join( ', ', @_ ) . " )";
  1258.    _debug 'exec()ing ', join " ", map "'$_'", @_ if _debugging_details;
  1259.  
  1260. #   {
  1261. ## Commented out since we don't call this on Win32.
  1262. #      # This works around the bug where 5.6.1 complains
  1263. #      # "Can't exec ...: No error" after an exec on NT, where
  1264. #      # exec() is simulated and actually returns in Perl's C
  1265. #      # code, though Perl's &exec does not...
  1266. #      no warnings "exec";
  1267. #
  1268. #      # Just in case the no warnings workaround
  1269. #      # stops beign a workaround, we don't want
  1270. #      # old values of $! causing spurious strerr()
  1271. #      # messages to appear in the "Can't exec" message
  1272. #      undef $!;
  1273.       exec @_;
  1274. #   }
  1275. #   croak "$!: exec( " . join( ', ', map "'$_'", @_ ) . " )";
  1276.     ## Fall through so $! can be reported to parent.
  1277. }
  1278.  
  1279.  
  1280. sub _sysopen {
  1281.    confess 'undef' unless defined $_[0] && defined $_[1];
  1282. _debug sprintf( "O_RDONLY=0x%02x ", O_RDONLY ),
  1283. sprintf( "O_WRONLY=0x%02x ", O_WRONLY ),
  1284. sprintf( "O_RDWR=0x%02x ", O_RDWR ),
  1285. sprintf( "O_TRUNC=0x%02x ", O_TRUNC),
  1286. sprintf( "O_CREAT=0x%02x ", O_CREAT),
  1287. sprintf( "O_APPEND=0x%02x ", O_APPEND),
  1288. if _debugging_details;
  1289.    my $r = POSIX::open( $_[0], $_[1], 0644 );
  1290.    croak "$!: open( $_[0], ", sprintf( "0x%03x", $_[1] ), " )" unless defined $r;
  1291.    _debug "open( $_[0], ", sprintf( "0x%03x", $_[1] ), " ) = $r"
  1292.       if _debugging_data;
  1293.    $fds{$r} = 1;
  1294.    return $r;
  1295. }
  1296.  
  1297. sub _pipe {
  1298.    ## Normal, blocking write for pipes that we read and the child writes,
  1299.    ## since most children expect writes to stdout to block rather than
  1300.    ## do a partial write.
  1301.    my ( $r, $w ) = POSIX::pipe;
  1302.    croak "$!: pipe()" unless defined $r;
  1303.    _debug "pipe() = ( $r, $w ) " if _debugging_details;
  1304.    $fds{$r} = $fds{$w} = 1;
  1305.    return ( $r, $w );
  1306. }
  1307.  
  1308. sub _pipe_nb {
  1309.    ## For pipes that we write, unblock the write side, so we can fill a buffer
  1310.    ## and continue to select().
  1311.    ## Contributed by Borislav Deianov <borislav@ensim.com>, with minor
  1312.    ## bugfix on fcntl result by me.
  1313.    local ( *R, *W );
  1314.    my $f = pipe( R, W );
  1315.    croak "$!: pipe()" unless defined $f;
  1316.    my ( $r, $w ) = ( fileno R, fileno W );
  1317.    _debug "pipe_nb pipe() = ( $r, $w )" if _debugging_details;
  1318.    unless ( Win32_MODE ) {
  1319.       ## POSIX::fcntl doesn't take fd numbers, so gotta use Perl's and
  1320.       ## then _dup the originals (which get closed on leaving this block)
  1321.       my $fres = fcntl( W, &F_SETFL, O_WRONLY | O_NONBLOCK );
  1322.       croak "$!: fcntl( $w, F_SETFL, O_NONBLOCK )" unless $fres;
  1323.       _debug "fcntl( $w, F_SETFL, O_NONBLOCK )" if _debugging_details;
  1324.    }
  1325.    ( $r, $w ) = ( _dup( $r ), _dup( $w ) );
  1326.    _debug "pipe_nb() = ( $r, $w )" if _debugging_details;
  1327.    return ( $r, $w );
  1328. }
  1329.  
  1330. sub _pty {
  1331.    require IO::Pty;
  1332.    my $pty = IO::Pty->new();
  1333.    croak "$!: pty ()" unless $pty;
  1334.    $pty->autoflush();
  1335.    $pty->blocking( 0 ) or croak "$!: pty->blocking ( 0 )";
  1336.    _debug "pty() = ( ", $pty->fileno, ", ", $pty->slave->fileno, " )"
  1337.       if _debugging_details;
  1338.    $fds{$pty->fileno} = $fds{$pty->slave->fileno} = 1;
  1339.    return $pty;
  1340. }
  1341.  
  1342.  
  1343. sub _read {
  1344.    confess 'undef' unless defined $_[0];
  1345.    my $s  = '';
  1346.    my $r = POSIX::read( $_[0], $s, 10_000 );
  1347.    croak "$!: read( $_[0] )" if not($r) and $! != POSIX::EINTR;
  1348.    $r ||= 0;
  1349.    _debug "read( $_[0] ) = $r chars '$s'" if _debugging_data;
  1350.    return $s;
  1351. }
  1352.  
  1353.  
  1354. ## A METHOD, not a function.
  1355. sub _spawn {
  1356.    my IPC::Run $self = shift;
  1357.    my ( $kid ) = @_;
  1358.  
  1359.    _debug "opening sync pipe ", $kid->{PID} if _debugging_details;
  1360.    my $sync_reader_fd;
  1361.    ( $sync_reader_fd, $self->{SYNC_WRITER_FD} ) = _pipe;
  1362.    $kid->{PID} = fork();
  1363.    croak "$! during fork" unless defined $kid->{PID};
  1364.  
  1365.    unless ( $kid->{PID} ) {
  1366.       ## _do_kid_and_exit closes sync_reader_fd since it closes all unwanted and
  1367.       ## unloved fds.
  1368.       $self->_do_kid_and_exit( $kid );
  1369.    }
  1370.    _debug "fork() = ", $kid->{PID} if _debugging_details;
  1371.  
  1372.    ## Wait for kid to get to it's exec() and see if it fails.
  1373.    _close $self->{SYNC_WRITER_FD};
  1374.    my $sync_pulse = _read $sync_reader_fd;
  1375.    _close $sync_reader_fd;
  1376.  
  1377.    if ( ! defined $sync_pulse || length $sync_pulse ) {
  1378.       if ( waitpid( $kid->{PID}, 0 ) >= 0 ) {
  1379.      $kid->{RESULT} = $?;
  1380.       }
  1381.       else {
  1382.      $kid->{RESULT} = -1;
  1383.       }
  1384.       $sync_pulse =
  1385.          "error reading synchronization pipe for $kid->{NUM}, pid $kid->{PID}"
  1386.      unless length $sync_pulse;
  1387.       croak $sync_pulse;
  1388.    }
  1389.    return $kid->{PID};
  1390.  
  1391. ## Wait for pty to get set up.  This is a hack until we get synchronous
  1392. ## selects.
  1393. if ( keys %{$self->{PTYS}} && $IO::Pty::VERSION < 0.9 ) {
  1394. _debug "sleeping to give pty a chance to init, will fix when newer IO::Pty arrives.";
  1395. sleep 1;
  1396. }
  1397. }
  1398.  
  1399.  
  1400. sub _write {
  1401.    confess 'undef' unless defined $_[0] && defined $_[1];
  1402.    my $r = POSIX::write( $_[0], $_[1], length $_[1] );
  1403.    croak "$!: write( $_[0], '$_[1]' )" unless $r;
  1404.    _debug "write( $_[0], '$_[1]' ) = $r" if _debugging_data;
  1405.    return $r;
  1406. }
  1407.  
  1408. =pod
  1409.  
  1410. =over
  1411.  
  1412. =item run
  1413.  
  1414. Run takes a harness or harness specification and runs it, pumping
  1415. all input to the child(ren), closing the input pipes when no more
  1416. input is available, collecting all output that arrives, until the
  1417. pipes delivering output are closed, then waiting for the children to
  1418. exit and reaping their result codes.
  1419.  
  1420. You may think of C<run( ... )> as being like 
  1421.  
  1422.    start( ... )->finish();
  1423.  
  1424. , though there is one subtle difference: run() does not
  1425. set \$input_scalars to '' like finish() does.  If an exception is thrown
  1426. from run(), all children will be killed off "gently", and then "annihilated"
  1427. if they do not go gently (in to that dark night. sorry).
  1428.  
  1429. If any exceptions are thrown, this does a L</kill_kill> before propogating
  1430. them.
  1431.  
  1432. =cut
  1433.  
  1434. use vars qw( $in_run );  ## No, not Enron;)
  1435.  
  1436. sub run {
  1437.    local $in_run = 1;  ## Allow run()-only optimizations.
  1438.    my IPC::Run $self = start( @_ );
  1439.    my $r = eval {
  1440.       $self->{clear_ins} = 0;
  1441.       $self->finish;
  1442.    };
  1443.    if ( $@ ) {
  1444.       my $x = $@;
  1445.       $self->kill_kill;
  1446.       die $x;
  1447.    }
  1448.    return $r;
  1449. }
  1450.  
  1451. =pod
  1452.  
  1453. =item signal
  1454.  
  1455.    ## To send it a specific signal by name ("USR1"):
  1456.    signal $h, "USR1";
  1457.    $h->signal ( "USR1" );
  1458.  
  1459. If $signal is provided and defined, sends a signal to all child processes.  Try
  1460. not to send numeric signals, use C<"KILL"> instead of C<9>, for instance.
  1461. Numeric signals aren't portable.
  1462.  
  1463. Throws an exception if $signal is undef.
  1464.  
  1465. This will I<not> clean up the harness, C<finish> it if you kill it.
  1466.  
  1467. Normally TERM kills a process gracefully (this is what the command line utility
  1468. C<kill> does by default), INT is sent by one of the keys C<^C>, C<Backspace> or
  1469. C<E<lt>DelE<gt>>, and C<QUIT> is used to kill a process and make it coredump.
  1470.  
  1471. The C<HUP> signal is often used to get a process to "restart", rereading 
  1472. config files, and C<USR1> and C<USR2> for really application-specific things.
  1473.  
  1474. Often, running C<kill -l> (that's a lower case "L") on the command line will
  1475. list the signals present on your operating system.
  1476.  
  1477. B<WARNING>: The signal subsystem is not at all portable.  We *may* offer
  1478. to simulate C<TERM> and C<KILL> on some operating systems, submit code
  1479. to me if you want this.
  1480.  
  1481. B<WARNING 2>: Up to and including perl v5.6.1, doing almost anything in a
  1482. signal handler could be dangerous.  The most safe code avoids all
  1483. mallocs and system calls, usually by preallocating a flag before
  1484. entering the signal handler, altering the flag's value in the
  1485. handler, and responding to the changed value in the main system:
  1486.  
  1487.    my $got_usr1 = 0;
  1488.    sub usr1_handler { ++$got_signal }
  1489.  
  1490.    $SIG{USR1} = \&usr1_handler;
  1491.    while () { sleep 1; print "GOT IT" while $got_usr1--; }
  1492.  
  1493. Even this approach is perilous if ++ and -- aren't atomic on your system
  1494. (I've never heard of this on any modern CPU large enough to run perl).
  1495.  
  1496. =cut
  1497.  
  1498. sub signal {
  1499.    my IPC::Run $self = shift;
  1500.  
  1501.    local $cur_self = $self;
  1502.  
  1503.    $self->_kill_kill_kill_pussycat_kill unless @_;
  1504.  
  1505.    Carp::cluck "Ignoring extra parameters passed to kill()" if @_ > 1;
  1506.  
  1507.    my ( $signal ) = @_;
  1508.    croak "Undefined signal passed to signal" unless defined $signal;
  1509.    for ( grep $_->{PID} && ! defined $_->{RESULT}, @{$self->{KIDS}} ) {
  1510.       _debug "sending $signal to $_->{PID}"
  1511.          if _debugging;
  1512.       kill $signal, $_->{PID}
  1513.          or _debugging && _debug "$! sending $signal to $_->{PID}";
  1514.    }
  1515.    
  1516.    return;
  1517. }
  1518.  
  1519. =pod
  1520.  
  1521. =item kill_kill
  1522.  
  1523.    ## To kill off a process:
  1524.    $h->kill_kill;
  1525.    kill_kill $h;
  1526.  
  1527.    ## To specify the grace period other than 30 seconds:
  1528.    kill_kill $h, grace => 5;
  1529.  
  1530.    ## To send QUIT instead of KILL if a process refuses to die:
  1531.    kill_kill $h, coup_d_grace => "QUIT";
  1532.  
  1533. Sends a C<TERM>, waits for all children to exit for up to 30 seconds, then
  1534. sends a C<KILL> to any that survived the C<TERM>.
  1535.  
  1536. Will wait for up to 30 more seconds for the OS to successfully C<KILL> the
  1537. processes.
  1538.  
  1539. The 30 seconds may be overridden by setting the C<grace> option, this
  1540. overrides both timers.
  1541.  
  1542. The harness is then cleaned up.
  1543.  
  1544. The doubled name indicates that this function may kill again and avoids
  1545. colliding with the core Perl C<kill> function.
  1546.  
  1547. Returns a 1 if the C<TERM> was sufficient, or a 0 if C<KILL> was 
  1548. required.  Throws an exception if C<KILL> did not permit the children
  1549. to be reaped.
  1550.  
  1551. B<NOTE>: The grace period is actually up to 1 second longer than that
  1552. given.  This is because the granularity of C<time> is 1 second.  Let me
  1553. know if you need finer granularity, we can leverage Time::HiRes here.
  1554.  
  1555. B<Win32>: Win32 does not know how to send real signals, so C<TERM> is
  1556. a full-force kill on Win32.  Thus all talk of grace periods, etc. do
  1557. not apply to Win32.
  1558.  
  1559. =cut
  1560.  
  1561. sub kill_kill {
  1562.    my IPC::Run $self = shift;
  1563.  
  1564.    my %options = @_;
  1565.    my $grace = $options{grace};
  1566.    $grace = 30 unless defined $grace;
  1567.    ++$grace; ## Make grace time a _minimum_
  1568.  
  1569.    my $coup_d_grace = $options{coup_d_grace};
  1570.    $coup_d_grace = "KILL" unless defined $coup_d_grace;
  1571.  
  1572.    delete $options{$_} for qw( grace coup_d_grace );
  1573.    Carp::cluck "Ignoring unknown options for kill_kill: ",
  1574.        join " ",keys %options
  1575.        if keys %options;
  1576.  
  1577.    $self->signal( "TERM" );
  1578.  
  1579.    my $quitting_time = time + $grace;
  1580.    my $delay = 0.01;
  1581.    my $accum_delay;
  1582.  
  1583.    my $have_killed_before;
  1584.  
  1585.    while () {
  1586.       ## delay first to yeild to other processes
  1587.       select undef, undef, undef, $delay;
  1588.       $accum_delay += $delay;
  1589.  
  1590.       $self->reap_nb;
  1591.       last unless $self->_running_kids;
  1592.  
  1593.       if ( $accum_delay >= $grace*0.8 ) {
  1594.          ## No point in checking until delay has grown some.
  1595.          if ( time >= $quitting_time ) {
  1596.             if ( ! $have_killed_before ) {
  1597.                $self->signal( $coup_d_grace );
  1598.                $have_killed_before = 1;
  1599.                $quitting_time += $grace;
  1600.                $delay = 0.01;
  1601.                $accum_delay = 0;
  1602.                next;
  1603.             }
  1604.             croak "Unable to reap all children, even after KILLing them"
  1605.          }
  1606.       }
  1607.  
  1608.       $delay *= 2;
  1609.       $delay = 0.5 if $delay >= 0.5;
  1610.    }
  1611.  
  1612.    $self->_cleanup;
  1613.    return $have_killed_before;
  1614. }
  1615.  
  1616. =pod
  1617.  
  1618. =item harness
  1619.  
  1620. Takes a harness specification and returns a harness.  This harness is
  1621. blessed in to IPC::Run, allowing you to use method call syntax for
  1622. run(), start(), et al if you like.
  1623.  
  1624. harness() is provided so that you can pre-build harnesses if you
  1625. would like to, but it's not required..
  1626.  
  1627. You may proceed to run(), start() or pump() after calling harness() (pump()
  1628. calls start() if need be).  Alternatively, you may pass your
  1629. harness specification to run() or start() and let them harness() for
  1630. you.  You can't pass harness specifications to pump(), though.
  1631.  
  1632. =cut
  1633.  
  1634. ##
  1635. ## Notes: I've avoided handling a scalar that doesn't look like an
  1636. ## opcode as a here document or as a filename, though I could DWIM
  1637. ## those.  I'm not sure that the advantages outweight the danger when
  1638. ## the DWIMer guesses wrong.
  1639. ##
  1640. ## TODO: allow user to spec default shell. Hmm, globally, in the
  1641. ## lexical scope hash, or per instance?  'Course they can do that
  1642. ## now by using a [...] to hold the command.
  1643. ##
  1644. my $harness_id = 0;
  1645. sub harness {
  1646.    my $options;
  1647.    if ( @_ && ref $_[-1] eq 'HASH' ) {
  1648.       $options = pop;
  1649.       require Data::Dumper;
  1650.       carp "Passing in options as a hash is deprecated:\n", Data::Dumper::Dumper( $options );
  1651.    }
  1652.  
  1653. #   local $IPC::Run::debug = $options->{debug}
  1654. #      if $options && defined $options->{debug};
  1655.  
  1656.    my @args;
  1657.    if ( @_ == 1 && ! ref $_[0] ) {
  1658.       if ( Win32_MODE ) {
  1659.          my $command = $ENV{ComSpec} || 'cmd';
  1660.          @args = ( [ $command, '/c', win32_parse_cmd_line $_[0] ] );
  1661.       }
  1662.       else {
  1663.          @args = ( [ qw( sh -c ), @_ ] );
  1664.       }
  1665.    }
  1666.    elsif ( @_ > 1 && ! grep ref $_, @_ ) {
  1667.       @args = ( [ @_ ] );
  1668.    }
  1669.    else {
  1670.       @args = @_;
  1671.    }
  1672.  
  1673.    my @errs;               # Accum errors, emit them when done.
  1674.  
  1675.    my $succinct;           # set if no redir ops are required yet.  Cleared
  1676.                             # if an op is seen.
  1677.  
  1678.    my $cur_kid;            # references kid or handle being parsed
  1679.  
  1680.    my $assumed_fd    = 0;  # fd to assume in succinct mode (no redir ops)
  1681.    my $handle_num    = 0;  # 1... is which handle we're parsing
  1682.  
  1683.    my IPC::Run $self = bless {}, __PACKAGE__;
  1684.  
  1685.    local $cur_self = $self;
  1686.  
  1687.    $self->{ID}    = ++$harness_id;
  1688.    $self->{IOS}   = [];
  1689.    $self->{KIDS}  = [];
  1690.    $self->{PIPES} = [];
  1691.    $self->{PTYS}  = {};
  1692.    $self->{STATE} = _newed;
  1693.  
  1694.    if ( $options ) {
  1695.       $self->{$_} = $options->{$_}
  1696.          for keys %$options;
  1697.    }
  1698.  
  1699.    _debug "****** harnessing *****" if _debugging;
  1700.  
  1701.    my $first_parse;
  1702.    local $_;
  1703.    my $arg_count = @args;
  1704.    while ( @args ) { for ( shift @args ) {
  1705.       eval {
  1706.          $first_parse = 1;
  1707.          _debug(
  1708.             "parsing ",
  1709.             defined $_
  1710.                ? ref $_ eq 'ARRAY'
  1711.                   ? ( '[ ', join( ', ', map "'$_'", @$_ ), ' ]' )
  1712.                   : ( ref $_
  1713.                      || ( length $_ < 50
  1714.                            ? "'$_'"
  1715.                            : join( '', "'", substr( $_, 0, 10 ), "...'" )
  1716.                         )
  1717.                   )
  1718.                : '<undef>'
  1719.          ) if _debugging;
  1720.  
  1721.       REPARSE:
  1722.          if ( ref eq 'ARRAY' || ( ! $cur_kid && ref eq 'CODE' ) ) {
  1723.             croak "Process control symbol ('|', '&') missing" if $cur_kid;
  1724.             croak "Can't spawn a subroutine on Win32"
  1725.            if Win32_MODE && ref eq "CODE";
  1726.             $cur_kid = {
  1727.                TYPE   => 'cmd',
  1728.                VAL    => $_,
  1729.                NUM    => @{$self->{KIDS}} + 1,
  1730.                OPS    => [],
  1731.                PID    => '',
  1732.                RESULT => undef,
  1733.             };
  1734.             push @{$self->{KIDS}}, $cur_kid;
  1735.             $succinct = 1;
  1736.          }
  1737.  
  1738.          elsif ( UNIVERSAL::isa( $_, 'IPC::Run::IO' ) ) {
  1739.             push @{$self->{IOS}}, $_;
  1740.             $cur_kid = undef;
  1741.             $succinct = 1;
  1742.          }
  1743.          
  1744.          elsif ( UNIVERSAL::isa( $_, 'IPC::Run::Timer' ) ) {
  1745.             push @{$self->{TIMERS}}, $_;
  1746.             $cur_kid = undef;
  1747.             $succinct = 1;
  1748.          }
  1749.          
  1750.          elsif ( /^(\d*)>&(\d+)$/ ) {
  1751.             croak "No command before '$_'" unless $cur_kid;
  1752.             push @{$cur_kid->{OPS}}, {
  1753.                TYPE => 'dup',
  1754.                KFD1 => $2,
  1755.                KFD2 => length $1 ? $1 : 1,
  1756.             };
  1757.             _debug "redirect operators now required" if _debugging_details;
  1758.             $succinct = ! $first_parse;
  1759.          }
  1760.  
  1761.          elsif ( /^(\d*)<&(\d+)$/ ) {
  1762.             croak "No command before '$_'" unless $cur_kid;
  1763.             push @{$cur_kid->{OPS}}, {
  1764.                TYPE => 'dup',
  1765.                KFD1 => $2,
  1766.                KFD2 => length $1 ? $1 : 0,
  1767.             };
  1768.             $succinct = ! $first_parse;
  1769.          }
  1770.  
  1771.          elsif ( /^(\d*)<&-$/ ) {
  1772.             croak "No command before '$_'" unless $cur_kid;
  1773.             push @{$cur_kid->{OPS}}, {
  1774.                TYPE => 'close',
  1775.                KFD  => length $1 ? $1 : 0,
  1776.             };
  1777.             $succinct = ! $first_parse;
  1778.          }
  1779.  
  1780.          elsif (
  1781.                /^(\d*) (<pipe)()            ()  ()  $/x
  1782.             || /^(\d*) (<pty) ((?:\s+\S+)?) (<) ()  $/x
  1783.             || /^(\d*) (<)    ()            ()  (.*)$/x
  1784.          ) {
  1785.             croak "No command before '$_'" unless $cur_kid;
  1786.  
  1787.             $succinct = ! $first_parse;
  1788.  
  1789.             my $type = $2 . $4;
  1790.  
  1791.             my $kfd = length $1 ? $1 : 0;
  1792.  
  1793.             my $pty_id;
  1794.             if ( $type eq '<pty<' ) {
  1795.                $pty_id = length $3 ? $3 : '0';
  1796.                ## do the require here to cause early error reporting
  1797.                require IO::Pty;
  1798.                ## Just flag the pyt's existence for now.  It'll be
  1799.                ## converted to a real IO::Pty by _open_pipes.
  1800.                $self->{PTYS}->{$pty_id} = undef;
  1801.             }
  1802.  
  1803.             my $source = $5;
  1804.  
  1805.             my @filters;
  1806.             my $binmode;
  1807.  
  1808.             unless ( length $source ) {
  1809.                if ( ! $succinct ) {
  1810.                   while ( @args > 1
  1811.                       && (
  1812.                          ( ref $args[1] && ! UNIVERSAL::isa $args[1], "IPC::Run::Timer" )
  1813.                          || UNIVERSAL::isa $args[0], "IPC::Run::binmode_pseudo_filter"
  1814.                       )
  1815.                   ) {
  1816.                      if ( UNIVERSAL::isa $args[0], "IPC::Run::binmode_pseudo_filter" ) {
  1817.                         $binmode = shift( @args )->();
  1818.                      }
  1819.                      else {
  1820.                         push @filters, shift @args
  1821.                      }
  1822.                   }
  1823.                }
  1824.                $source = shift @args;
  1825.                croak "'$_' missing a source" if _empty $source;
  1826.  
  1827.                _debug(
  1828.                   'Kid ', $cur_kid->{NUM}, "'s input fd ", $kfd,
  1829.                   ' has ', scalar( @filters ), ' filters.'
  1830.                ) if _debugging_details && @filters;
  1831.             };
  1832.  
  1833.             my IPC::Run::IO $pipe = IPC::Run::IO->_new_internal(
  1834.                $type, $kfd, $pty_id, $source, $binmode, @filters
  1835.             );
  1836.  
  1837.             if ( ( ref $source eq 'GLOB' || UNIVERSAL::isa $source, 'IO::Handle' )
  1838.                && $type !~ /^<p(ty<|ipe)$/
  1839.             ) {
  1840.            _debug "setting DONT_CLOSE" if _debugging_details;
  1841.                $pipe->{DONT_CLOSE} = 1; ## this FD is not closed by us.
  1842.            _dont_inherit( $source ) if Win32_MODE;
  1843.             }
  1844.  
  1845.             push @{$cur_kid->{OPS}}, $pipe;
  1846.       }
  1847.  
  1848.          elsif ( /^()   (>>?)  (&)     ()      (.*)$/x
  1849.             ||   /^()   (&)    (>pipe) ()      ()  $/x 
  1850.             ||   /^()   (>pipe)(&)     ()      ()  $/x 
  1851.             ||   /^(\d*)()     (>pipe) ()      ()  $/x
  1852.             ||   /^()   (&)    (>pty)  ( \w*)> ()  $/x 
  1853. ## TODO:    ||   /^()   (>pty) (\d*)> (&) ()  $/x 
  1854.             ||   /^(\d*)()     (>pty)  ( \w*)> ()  $/x
  1855.             ||   /^()   (&)    (>>?)   ()      (.*)$/x 
  1856.             ||   /^(\d*)()     (>>?)   ()      (.*)$/x
  1857.          ) {
  1858.             croak "No command before '$_'" unless $cur_kid;
  1859.  
  1860.             $succinct = ! $first_parse;
  1861.  
  1862.             my $type = (
  1863.                $2 eq '>pipe' || $3 eq '>pipe'
  1864.                   ? '>pipe'
  1865.                   : $2 eq '>pty' || $3 eq '>pty'
  1866.                      ? '>pty>'
  1867.                      : '>'
  1868.             );
  1869.             my $kfd = length $1 ? $1 : 1;
  1870.             my $trunc = ! ( $2 eq '>>' || $3 eq '>>' );
  1871.             my $pty_id = (
  1872.                $2 eq '>pty' || $3 eq '>pty'
  1873.                   ? length $4 ? $4 : 0
  1874.                   : undef
  1875.             );
  1876.  
  1877.             my $stderr_too =
  1878.                   $2 eq '&'
  1879.                || $3 eq '&'
  1880.                || ( ! length $1 && substr( $type, 0, 4 ) eq '>pty' );
  1881.  
  1882.             my $dest = $5;
  1883.             my @filters;
  1884.             my $binmode = 0;
  1885.             unless ( length $dest ) {
  1886.                if ( ! $succinct ) {
  1887.                   ## unshift...shift: '>' filters source...sink left...right
  1888.                   while ( @args > 1
  1889.                      && ( 
  1890.                         ( ref $args[1] && !  UNIVERSAL::isa $args[1], "IPC::Run::Timer" )
  1891.                         || UNIVERSAL::isa $args[0], "IPC::Run::binmode_pseudo_filter"
  1892.                      )
  1893.                   ) {
  1894.                      if ( UNIVERSAL::isa $args[0], "IPC::Run::binmode_pseudo_filter" ) {
  1895.                         $binmode = shift( @args )->();
  1896.                      }
  1897.                      else {
  1898.                         unshift @filters, shift @args;
  1899.                      }
  1900.                   }
  1901.                }
  1902.  
  1903.                $dest = shift @args;
  1904.  
  1905.                _debug(
  1906.                   'Kid ', $cur_kid->{NUM}, "'s output fd ", $kfd,
  1907.                   ' has ', scalar( @filters ), ' filters.'
  1908.                ) if _debugging_details && @filters;
  1909.  
  1910.                if ( $type eq '>pty>' ) {
  1911.                   ## do the require here to cause early error reporting
  1912.                   require IO::Pty;
  1913.                   ## Just flag the pyt's existence for now.  _open_pipes()
  1914.                   ## will new an IO::Pty for each key.
  1915.                   $self->{PTYS}->{$pty_id} = undef;
  1916.                }
  1917.             }
  1918.  
  1919.             croak "'$_' missing a destination" if _empty $dest;
  1920.             my $pipe = IPC::Run::IO->_new_internal(
  1921.                $type, $kfd, $pty_id, $dest, $binmode, @filters
  1922.             );
  1923.             $pipe->{TRUNC} = $trunc;
  1924.  
  1925.             if (  ( UNIVERSAL::isa( $dest, 'GLOB' ) || UNIVERSAL::isa( $dest, 'IO::Handle' ) )
  1926.                && $type !~ /^>(pty>|pipe)$/
  1927.             ) {
  1928.            _debug "setting DONT_CLOSE" if _debugging_details;
  1929.                $pipe->{DONT_CLOSE} = 1; ## this FD is not closed by us.
  1930.             }
  1931.             push @{$cur_kid->{OPS}}, $pipe;
  1932.             push @{$cur_kid->{OPS}}, {
  1933.                TYPE => 'dup',
  1934.                KFD1 => 1,
  1935.                KFD2 => 2,
  1936.             } if $stderr_too;
  1937.          }
  1938.  
  1939.          elsif ( $_ eq "|" ) {
  1940.             croak "No command before '$_'" unless $cur_kid;
  1941.             unshift @{$cur_kid->{OPS}}, {
  1942.                TYPE => '|',
  1943.                KFD  => 1,
  1944.             };
  1945.             $succinct   = 1;
  1946.             $assumed_fd = 1;
  1947.             $cur_kid    = undef;
  1948.          }
  1949.  
  1950.          elsif ( $_ eq "&" ) {
  1951.             croak "No command before '$_'" unless $cur_kid;
  1952.             unshift @{$cur_kid->{OPS}}, {
  1953.                TYPE => 'close',
  1954.                KFD  => 0,
  1955.             };
  1956.             $succinct   = 1;
  1957.             $assumed_fd = 0;
  1958.             $cur_kid    = undef;
  1959.          }
  1960.  
  1961.          elsif ( $_ eq 'init' ) {
  1962.             croak "No command before '$_'" unless $cur_kid;
  1963.             push @{$cur_kid->{OPS}}, {
  1964.                TYPE => 'init',
  1965.                SUB  => shift @args,
  1966.             };
  1967.          }
  1968.  
  1969.          elsif ( ! ref $_ ) {
  1970.             $self->{$_} = shift @args;
  1971.          }
  1972.  
  1973.          elsif ( $_ eq 'init' ) {
  1974.             croak "No command before '$_'" unless $cur_kid;
  1975.             push @{$cur_kid->{OPS}}, {
  1976.                TYPE => 'init',
  1977.                SUB  => shift @args,
  1978.             };
  1979.          }
  1980.  
  1981.          elsif ( $succinct && $first_parse ) {
  1982.             ## It's not an opcode, and no explicit opcodes have been
  1983.             ## seen yet, so assume it's a file name.
  1984.             unshift @args, $_;
  1985.             if ( ! $assumed_fd ) {
  1986.                $_ = "$assumed_fd<",
  1987.             }
  1988.             else {
  1989.                $_ = "$assumed_fd>",
  1990.             }
  1991.             _debug "assuming '", $_, "'" if _debugging_details;
  1992.             ++$assumed_fd;
  1993.             $first_parse = 0;
  1994.             goto REPARSE;
  1995.          }
  1996.  
  1997.          else {
  1998.             croak join( 
  1999.                '',
  2000.                'Unexpected ',
  2001.                ( ref() ? $_ : 'scalar' ),
  2002.                ' in harness() parameter ',
  2003.                $arg_count - @args
  2004.             );
  2005.          }
  2006.       };
  2007.       if ( $@ ) {
  2008.          push @errs, $@;
  2009.          _debug 'caught ', $@ if _debugging;
  2010.       }
  2011.    } }
  2012.  
  2013.    die join( '', @errs ) if @errs;
  2014.  
  2015.  
  2016.    $self->{STATE} = _harnessed;
  2017. #   $self->timeout( $options->{timeout} ) if exists $options->{timeout};
  2018.    return $self;
  2019. }
  2020.  
  2021.  
  2022. sub _open_pipes {
  2023.    my IPC::Run $self = shift;
  2024.  
  2025.    my @errs;
  2026.  
  2027.    my @close_on_fail;
  2028.  
  2029.    ## When a pipe character is seen, a pipe is created.  $pipe_read_fd holds
  2030.    ## the dangling read end of the pipe until we get to the next process.
  2031.    my $pipe_read_fd;
  2032.  
  2033.    ## Output descriptors for the last command are shared by all children.
  2034.    ## @output_fds_accum accumulates the current set of output fds.
  2035.    my @output_fds_accum;
  2036.  
  2037.    for ( sort keys %{$self->{PTYS}} ) {
  2038.       _debug "opening pty '", $_, "'" if _debugging_details;
  2039.       my $pty = _pty;
  2040.       $self->{PTYS}->{$_} = $pty;
  2041.    }
  2042.  
  2043.    for ( @{$self->{IOS}} ) {
  2044.       eval { $_->init; };
  2045.       if ( $@ ) {
  2046.          push @errs, $@;
  2047.          _debug 'caught ', $@ if _debugging;
  2048.       }
  2049.       else {
  2050.          push @close_on_fail, $_;
  2051.       }
  2052.    }
  2053.  
  2054.    ## Loop through the kids and their OPS, interpreting any that require
  2055.    ## parent-side actions.
  2056.    for my $kid ( @{$self->{KIDS}} ) {
  2057.       unless ( ref $kid->{VAL} eq 'CODE' ) {
  2058.          $kid->{PATH} = _search_path $kid->{VAL}->[0];
  2059.       }
  2060.       if ( defined $pipe_read_fd ) {
  2061.      _debug "placing write end of pipe on kid $kid->{NUM}'s stdin"
  2062.         if _debugging_details;
  2063.          unshift @{$kid->{OPS}}, {
  2064.             TYPE => 'PIPE',  ## Prevent next loop from triggering on this
  2065.             KFD  => 0,
  2066.             TFD  => $pipe_read_fd,
  2067.          };
  2068.          $pipe_read_fd = undef;
  2069.       }
  2070.       @output_fds_accum = ();
  2071.       for my $op ( @{$kid->{OPS}} ) {
  2072. #         next if $op->{IS_DEBUG};
  2073.          my $ok = eval {
  2074.             if ( $op->{TYPE} eq '<' ) {
  2075.                my $source = $op->{SOURCE};
  2076.            if ( ! ref $source ) {
  2077.           _debug(
  2078.              "kid ", $kid->{NUM}, " to read ", $op->{KFD},
  2079.              " from '" .  $source, "' (read only)"
  2080.           ) if _debugging_details;
  2081.           croak "simulated open failure"
  2082.              if $self->{_simulate_open_failure};
  2083.           $op->{TFD} = _sysopen( $source, O_RDONLY );
  2084.           push @close_on_fail, $op->{TFD};
  2085.            }
  2086.            elsif ( UNIVERSAL::isa( $source, 'GLOB' )
  2087.           ||   UNIVERSAL::isa( $source, 'IO::Handle' )
  2088.            ) {
  2089.           croak
  2090.              "Unopened filehandle in input redirect for $op->{KFD}"
  2091.              unless defined fileno $source;
  2092.           $op->{TFD} = fileno $source;
  2093.           _debug(
  2094.              "kid ", $kid->{NUM}, " to read ", $op->{KFD},
  2095.              " from fd ", $op->{TFD}
  2096.           ) if _debugging_details;
  2097.            }
  2098.            elsif ( UNIVERSAL::isa( $source, 'SCALAR' ) ) {
  2099.           _debug(
  2100.              "kid ", $kid->{NUM}, " to read ", $op->{KFD},
  2101.              " from SCALAR"
  2102.           ) if _debugging_details;
  2103.  
  2104.           $op->open_pipe( $self->_debug_fd );
  2105.           push @close_on_fail, $op->{KFD}, $op->{FD};
  2106.  
  2107.           my $s = '';
  2108.           $op->{KIN_REF} = \$s;
  2109.            }
  2110.            elsif ( UNIVERSAL::isa( $source, 'CODE' ) ) {
  2111.           _debug(
  2112.              'kid ', $kid->{NUM}, ' to read ', $op->{KFD}, ' from CODE'
  2113.           ) if _debugging_details;
  2114.           
  2115.           $op->open_pipe( $self->_debug_fd );
  2116.           push @close_on_fail, $op->{KFD}, $op->{FD};
  2117.           
  2118.           my $s = '';
  2119.           $op->{KIN_REF} = \$s;
  2120.            }
  2121.            else {
  2122.           croak(
  2123.              "'"
  2124.              . ref( $source )
  2125.              . "' not allowed as a source for input redirection"
  2126.           );
  2127.            }
  2128.                $op->_init_filters;
  2129.             }
  2130.             elsif ( $op->{TYPE} eq '<pipe' ) {
  2131.                _debug(
  2132.                   'kid to read ', $op->{KFD},
  2133.                   ' from a pipe IPC::Run opens and returns',
  2134.                ) if _debugging_details;
  2135.  
  2136.                my ( $r, $w ) = $op->open_pipe( $self->_debug_fd, $op->{SOURCE} );
  2137.            _debug "caller will write to ", fileno $op->{SOURCE}
  2138.               if _debugging_details;
  2139.  
  2140.                $op->{TFD}    = $r;
  2141.            $op->{FD}     = undef; # we don't manage this fd
  2142.                $op->_init_filters;
  2143.             }
  2144.             elsif ( $op->{TYPE} eq '<pty<' ) {
  2145.                _debug(
  2146.                   'kid to read ', $op->{KFD}, " from pty '", $op->{PTY_ID}, "'",
  2147.                ) if _debugging_details;
  2148.                
  2149.                for my $source ( $op->{SOURCE} ) {
  2150.                   if ( UNIVERSAL::isa( $source, 'SCALAR' ) ) {
  2151.                      _debug(
  2152.                         "kid ", $kid->{NUM}, " to read ", $op->{KFD},
  2153.                         " from SCALAR via pty '", $op->{PTY_ID}, "'"
  2154.                      ) if _debugging_details;
  2155.  
  2156.                      my $s = '';
  2157.                      $op->{KIN_REF} = \$s;
  2158.                   }
  2159.                   elsif ( UNIVERSAL::isa( $source, 'CODE' ) ) {
  2160.                      _debug(
  2161.                         "kid ", $kid->{NUM}, " to read ", $op->{KFD},
  2162.                         " from CODE via pty '", $op->{PTY_ID}, "'"
  2163.                      ) if _debugging_details;
  2164.                      my $s = '';
  2165.                      $op->{KIN_REF} = \$s;
  2166.                   }
  2167.                   else {
  2168.                      croak(
  2169.                         "'"
  2170.                         . ref( $source )
  2171.                         . "' not allowed as a source for '<pty<' redirection"
  2172.                      );
  2173.                   }
  2174.                }
  2175.                $op->{FD} = $self->{PTYS}->{$op->{PTY_ID}}->fileno;
  2176.                $op->{TFD} = undef; # The fd isn't known until after fork().
  2177.                $op->_init_filters;
  2178.             }
  2179.             elsif ( $op->{TYPE} eq '>' ) {
  2180.                ## N> output redirection.
  2181.                my $dest = $op->{DEST};
  2182.                if ( ! ref $dest ) {
  2183.                   _debug(
  2184.                      "kid ", $kid->{NUM}, " to write ", $op->{KFD},
  2185.                      " to '", $dest, "' (write only, create, ",
  2186.                      ( $op->{TRUNC} ? 'truncate' : 'append' ),
  2187.                      ")"
  2188.                   ) if _debugging_details;
  2189.                   croak "simulated open failure"
  2190.                      if $self->{_simulate_open_failure};
  2191.                   $op->{TFD} = _sysopen(
  2192.                      $dest,
  2193.                      ( O_WRONLY
  2194.                      | O_CREAT 
  2195.                      | ( $op->{TRUNC} ? O_TRUNC : O_APPEND )
  2196.                      )
  2197.                   );
  2198.           if ( Win32_MODE ) {
  2199.              ## I have no idea why this is needed to make the current
  2200.              ## file position survive the gyrations TFD must go 
  2201.              ## through...
  2202.              POSIX::lseek( $op->{TFD}, 0, POSIX::SEEK_END() );
  2203.           }
  2204.                   push @close_on_fail, $op->{TFD};
  2205.                }
  2206.                elsif ( UNIVERSAL::isa( $dest, 'GLOB' ) ) {
  2207.                   croak(
  2208.                    "Unopened filehandle in output redirect, command $kid->{NUM}"
  2209.                   ) unless defined fileno $dest;
  2210.                   ## Turn on autoflush, mostly just to flush out
  2211.                   ## existing output.
  2212.                   my $old_fh = select( $dest ); $| = 1; select( $old_fh );
  2213.                   $op->{TFD} = fileno $dest;
  2214.                   _debug(
  2215.                      'kid to write ', $op->{KFD}, ' to handle ', $op->{TFD}
  2216.                   ) if _debugging_details;
  2217.                }
  2218.                elsif ( UNIVERSAL::isa( $dest, 'SCALAR' ) ) {
  2219.                   _debug(
  2220.                      "kid ", $kid->{NUM}, " to write $op->{KFD} to SCALAR"
  2221.                   ) if _debugging_details;
  2222.  
  2223.           $op->open_pipe( $self->_debug_fd );
  2224.                   push @close_on_fail, $op->{FD}, $op->{TFD};
  2225.                   $$dest = '' if $op->{TRUNC};
  2226.                }
  2227.                elsif ( UNIVERSAL::isa( $dest, 'CODE' ) ) {
  2228.                   _debug(
  2229.                      "kid $kid->{NUM} to write $op->{KFD} to CODE"
  2230.                   ) if _debugging_details;
  2231.  
  2232.           $op->open_pipe( $self->_debug_fd );
  2233.                   push @close_on_fail, $op->{FD}, $op->{TFD};
  2234.                }
  2235.                else {
  2236.                   croak(
  2237.                      "'"
  2238.                      . ref( $dest )
  2239.                      . "' not allowed as a sink for output redirection"
  2240.                   );
  2241.                }
  2242.                $output_fds_accum[$op->{KFD}] = $op;
  2243.                $op->_init_filters;
  2244.             }
  2245.  
  2246.             elsif ( $op->{TYPE} eq '>pipe' ) {
  2247.                ## N> output redirection to a pipe we open, but don't select()
  2248.                ## on.
  2249.                _debug(
  2250.                   "kid ", $kid->{NUM}, " to write ", $op->{KFD},
  2251.           ' to a pipe IPC::Run opens and returns'
  2252.                ) if _debugging_details;
  2253.  
  2254.                my ( $r, $w ) = $op->open_pipe( $self->_debug_fd, $op->{DEST} );
  2255.            _debug "caller will read from ", fileno $op->{DEST}
  2256.               if _debugging_details;
  2257.  
  2258.                $op->{TFD} = $w;
  2259.            $op->{FD}  = undef; # we don't manage this fd
  2260.                $op->_init_filters;
  2261.  
  2262.                $output_fds_accum[$op->{KFD}] = $op;
  2263.             }
  2264.             elsif ( $op->{TYPE} eq '>pty>' ) {
  2265.                my $dest = $op->{DEST};
  2266.                if ( UNIVERSAL::isa( $dest, 'SCALAR' ) ) {
  2267.                   _debug(
  2268.                      "kid ", $kid->{NUM}, " to write ", $op->{KFD},
  2269.                      " to SCALAR via pty '", $op->{PTY_ID}, "'"
  2270.                ) if _debugging_details;
  2271.  
  2272.                   $$dest = '' if $op->{TRUNC};
  2273.                }
  2274.                elsif ( UNIVERSAL::isa( $dest, 'CODE' ) ) {
  2275.                   _debug(
  2276.                      "kid ", $kid->{NUM}, " to write ", $op->{KFD},
  2277.                      " to CODE via pty '", $op->{PTY_ID}, "'"
  2278.                   ) if _debugging_details;
  2279.                }
  2280.                else {
  2281.                   croak(
  2282.                      "'"
  2283.                      . ref( $dest )
  2284.                      . "' not allowed as a sink for output redirection"
  2285.                   );
  2286.                }
  2287.  
  2288.                $op->{FD} = $self->{PTYS}->{$op->{PTY_ID}}->fileno;
  2289.                $op->{TFD} = undef; # The fd isn't known until after fork().
  2290.                $output_fds_accum[$op->{KFD}] = $op;
  2291.                $op->_init_filters;
  2292.             }
  2293.             elsif ( $op->{TYPE} eq '|' ) {
  2294.                _debug(
  2295.                   "pipelining $kid->{NUM} and "
  2296.                   . ( $kid->{NUM} + 1 )
  2297.                ) if _debugging_details;
  2298.                ( $pipe_read_fd, $op->{TFD} ) = _pipe;
  2299.            if ( Win32_MODE ) {
  2300.           _dont_inherit( $pipe_read_fd );
  2301.           _dont_inherit( $op->{TFD} );
  2302.            }
  2303.                @output_fds_accum = ();
  2304.             }
  2305.             elsif ( $op->{TYPE} eq '&' ) {
  2306.                @output_fds_accum = ();
  2307.             } # end if $op->{TYPE} tree
  2308.         1;
  2309.      }; # end eval
  2310.      unless ( $ok ) {
  2311.         push @errs, $@;
  2312.         _debug 'caught ', $@ if _debugging;
  2313.      }
  2314.       } # end for ( OPS }
  2315.    }
  2316.  
  2317.    if ( @errs ) {
  2318.       for ( @close_on_fail ) {
  2319.          _close( $_ );
  2320.          $_ = undef;
  2321.       }
  2322.       for ( keys %{$self->{PTYS}} ) {
  2323.          next unless $self->{PTYS}->{$_};
  2324.          close $self->{PTYS}->{$_};
  2325.          $self->{PTYS}->{$_} = undef;
  2326.       }
  2327.       die join( '', @errs )
  2328.    }
  2329.  
  2330.    ## give all but the last child all of the output file descriptors
  2331.    ## These will be reopened (and thus rendered useless) if the child
  2332.    ## dup2s on to these descriptors, since we unshift these.  This way
  2333.    ## each process emits output to the same file descriptors that the
  2334.    ## last child will write to.  This is probably not quite correct,
  2335.    ## since each child should write to the file descriptors inherited
  2336.    ## from the parent.
  2337.    ## TODO: fix the inheritance of output file descriptors.
  2338.    ## NOTE: This sharing of OPS among kids means that we can't easily put
  2339.    ## a kid number in each OPS structure to ping the kid when all ops
  2340.    ## have closed (when $self->{PIPES} has emptied).  This means that we
  2341.    ## need to scan the KIDS whenever @{$self->{PIPES}} is empty to see
  2342.    ## if there any of them are still alive.
  2343.    for ( my $num = 0; $num < $#{$self->{KIDS}}; ++$num ) {
  2344.       for ( reverse @output_fds_accum ) {
  2345.          next unless defined $_;
  2346.          _debug(
  2347.             'kid ', $self->{KIDS}->[$num]->{NUM}, ' also to write ', $_->{KFD},
  2348.             ' to ', ref $_->{DEST}
  2349.          ) if _debugging_details;
  2350.          unshift @{$self->{KIDS}->[$num]->{OPS}}, $_;
  2351.       }
  2352.    }
  2353.  
  2354.    ## Open the debug pipe if we need it
  2355.    ## Create the list of PIPES we need to scan and the bit vectors needed by
  2356.    ## select().  Do this first so that _cleanup can _clobber() them if an
  2357.    ## exception occurs.
  2358.    @{$self->{PIPES}} = ();
  2359.    $self->{RIN} = '';
  2360.    $self->{WIN} = '';
  2361.    $self->{EIN} = '';
  2362.    ## PIN is a vec()tor that indicates who's paused.
  2363.    $self->{PIN} = '';
  2364.    for my $kid ( @{$self->{KIDS}} ) {
  2365.       for ( @{$kid->{OPS}} ) {
  2366.          if ( defined $_->{FD} ) {
  2367.             _debug(
  2368.                'kid ', $kid->{NUM}, '[', $kid->{PID}, "]'s ", $_->{KFD},
  2369.                ' is my ', $_->{FD}
  2370.             ) if _debugging_details;
  2371.             vec( $self->{ $_->{TYPE} =~ /^</ ? 'WIN' : 'RIN' }, $_->{FD}, 1 ) = 1;
  2372. #        vec( $self->{EIN}, $_->{FD}, 1 ) = 1;
  2373.             push @{$self->{PIPES}}, $_;
  2374.          }
  2375.       }
  2376.    }
  2377.  
  2378.    for my $io ( @{$self->{IOS}} ) {
  2379.       my $fd = $io->fileno;
  2380.       vec( $self->{RIN}, $fd, 1 ) = 1 if $io->mode =~ /r/;
  2381.       vec( $self->{WIN}, $fd, 1 ) = 1 if $io->mode =~ /w/;
  2382. #      vec( $self->{EIN}, $fd, 1 ) = 1;
  2383.       push @{$self->{PIPES}}, $io;
  2384.    }
  2385.  
  2386.    ## Put filters on the end of the filter chains to read & write the pipes.
  2387.    ## Clear pipe states
  2388.    for my $pipe ( @{$self->{PIPES}} ) {
  2389.       $pipe->{SOURCE_EMPTY} = 0;
  2390.       $pipe->{PAUSED} = 0;
  2391.       if ( $pipe->{TYPE} =~ /^>/ ) {
  2392.          my $pipe_reader = sub {
  2393.             my ( undef, $out_ref ) = @_;
  2394.  
  2395.             return undef unless defined $pipe->{FD};
  2396.             return 0 unless vec( $self->{ROUT}, $pipe->{FD}, 1 );
  2397.  
  2398.             vec( $self->{ROUT}, $pipe->{FD}, 1 ) = 0;
  2399.  
  2400.             _debug_desc_fd( 'reading from', $pipe ) if _debugging_details;
  2401.             my $in = eval { _read( $pipe->{FD} ) };
  2402.             if ( $@ ) {
  2403.                $in = '';
  2404.                ## IO::Pty throws the Input/output error if the kid dies.
  2405.            ## read() throws the bad file descriptor message if the
  2406.            ## kid dies on Win32.
  2407.                die $@ unless
  2408.               $@ =~ /^Input\/output error: read/ ||
  2409.           ($@ =~ /input or output/ && $^O =~ /aix/) 
  2410.           || ( Win32_MODE && $@ =~ /Bad file descriptor/ );
  2411.             }
  2412.  
  2413.             unless ( length $in ) {
  2414.                $self->_clobber( $pipe );
  2415.                return undef;
  2416.             }
  2417.  
  2418.             ## Protect the position so /.../g matches may be used.
  2419.             my $pos = pos $$out_ref;
  2420.             $$out_ref .= $in;
  2421.             pos( $$out_ref ) = $pos;
  2422.             return 1;
  2423.          };
  2424.          ## Input filters are the last filters
  2425.          push @{$pipe->{FILTERS}}, $pipe_reader;
  2426.          push @{$self->{TEMP_FILTERS}}, $pipe_reader;
  2427.       }
  2428.       else {
  2429.          my $pipe_writer = sub {
  2430.             my ( $in_ref, $out_ref ) = @_;
  2431.             return undef unless defined $pipe->{FD};
  2432.             return 0
  2433.                unless vec( $self->{WOUT}, $pipe->{FD}, 1 )
  2434.                   || $pipe->{PAUSED};
  2435.  
  2436.             vec( $self->{WOUT}, $pipe->{FD}, 1 ) = 0;
  2437.  
  2438.             if ( ! length $$in_ref ) {
  2439.                if ( ! defined get_more_input ) {
  2440.                   $self->_clobber( $pipe );
  2441.                   return undef;
  2442.                }
  2443.             }
  2444.  
  2445.             unless ( length $$in_ref ) {
  2446.                unless ( $pipe->{PAUSED} ) {
  2447.                   _debug_desc_fd( 'pausing', $pipe ) if _debugging_details;
  2448.                   vec( $self->{WIN}, $pipe->{FD}, 1 ) = 0;
  2449. #          vec( $self->{EIN}, $pipe->{FD}, 1 ) = 0;
  2450.                   vec( $self->{PIN}, $pipe->{FD}, 1 ) = 1;
  2451.                   $pipe->{PAUSED} = 1;
  2452.                }
  2453.                return 0;
  2454.             }
  2455.             _debug_desc_fd( 'writing to', $pipe ) if _debugging_details;
  2456.  
  2457.             my $c = _write( $pipe->{FD}, $$in_ref );
  2458.             substr( $$in_ref, 0, $c, '' );
  2459.             return 1;
  2460.          };
  2461.          ## Output filters are the first filters
  2462.          unshift @{$pipe->{FILTERS}}, $pipe_writer;
  2463.          push    @{$self->{TEMP_FILTERS}}, $pipe_writer;
  2464.       }
  2465.    }
  2466. }
  2467.  
  2468.  
  2469. sub _dup2_gently {
  2470.    ## A METHOD, NOT A FUNCTION, NEEDS $self!
  2471.    my IPC::Run $self = shift;
  2472.    my ( $files, $fd1, $fd2 ) = @_;
  2473.    ## Moves TFDs that are using the destination fd out of the
  2474.    ## way before calling _dup2
  2475.    for ( @$files ) {
  2476.       next unless defined $_->{TFD};
  2477.       $_->{TFD} = _dup( $_->{TFD} ) if $_->{TFD} == $fd2;
  2478.    }
  2479.    $self->{DEBUG_FD} = _dup $self->{DEBUG_FD}
  2480.       if defined $self->{DEBUG_FD} && $self->{DEBUG_FD} == $fd2;
  2481.  
  2482.    _dup2_rudely( $fd1, $fd2 );
  2483. }
  2484.  
  2485. =pod
  2486.  
  2487. =item close_terminal
  2488.  
  2489. This is used as (or in) an init sub to cast off the bonds of a controlling
  2490. terminal.  It must precede all other redirection ops that affect
  2491. STDIN, STDOUT, or STDERR to be guaranteed effective.
  2492.  
  2493. =cut
  2494.  
  2495.  
  2496. sub close_terminal {
  2497.    ## Cast of the bonds of a controlling terminal
  2498.  
  2499.    POSIX::setsid() || croak "POSIX::setsid() failed";
  2500.    _debug "closing stdin, out, err"
  2501.       if _debugging_details;
  2502.    close STDIN;
  2503.    close STDERR;
  2504.    close STDOUT;
  2505. }
  2506.  
  2507.  
  2508. sub _do_kid_and_exit {
  2509.    my IPC::Run $self = shift;
  2510.    my ( $kid ) = @_;
  2511.  
  2512.    ## For unknown reasons, placing these two statements in the eval{}
  2513.    ## causes the eval {} to not catch errors after they are executed in
  2514.    ## perl 5.6.0, godforsaken version that it is...not sure about 5.6.1.
  2515.    ## Part of this could be that these symbols get destructed when
  2516.    ## exiting the eval, and that destruction might be what's (wrongly)
  2517.    ## confusing the eval{}, allowing the exception to probpogate.
  2518.    my $s1 = gensym;
  2519.    my $s2 = gensym;
  2520.  
  2521.    eval {
  2522.       local $cur_self = $self;
  2523.  
  2524.       _set_child_debug_name( ref $kid->{VAL} eq "CODE"
  2525.      ? "CODE"
  2526.      : basename( $kid->{VAL}->[0] )
  2527.       );
  2528.  
  2529.       ## close parent FD's first so they're out of the way.
  2530.       ## Don't close STDIN, STDOUT, STDERR: they should be inherited or
  2531.       ## overwritten below.
  2532.       my @needed = $self->{noinherit} ? () : ( 1, 1, 1 );
  2533.       $needed[ $self->{SYNC_WRITER_FD} ] = 1;
  2534.       $needed[ $self->{DEBUG_FD} ] = 1 if defined $self->{DEBUG_FD};
  2535.  
  2536.       for ( @{$kid->{OPS}} ) {
  2537.      $needed[ $_->{TFD} ] = 1 if defined $_->{TFD};
  2538.       }
  2539.  
  2540.       ## TODO: use the forthcoming IO::Pty to close the terminal and
  2541.       ## make the first pty for this child the controlling terminal.
  2542.       ## This will also make it so that pty-laden kids don't cause
  2543.       ## other kids to lose stdin/stdout/stderr.
  2544.       my @closed;
  2545.       if ( %{$self->{PTYS}} ) {
  2546.      ## Clean up the parent's fds.
  2547.      for ( keys %{$self->{PTYS}} ) {
  2548.         _debug "Cleaning up parent's ptty '$_'" if _debugging_details;
  2549.         my $slave = $self->{PTYS}->{$_}->slave;
  2550.         $closed[ $self->{PTYS}->{$_}->fileno ] = 1;
  2551.         close $self->{PTYS}->{$_};
  2552.         $self->{PTYS}->{$_} = $slave;
  2553.      }
  2554.  
  2555.      close_terminal;
  2556.      $closed[ $_ ] = 1 for ( 0..2 );
  2557.       }
  2558.  
  2559.       for my $sibling ( @{$self->{KIDS}} ) {
  2560.      for ( @{$sibling->{OPS}} ) {
  2561.         if ( $_->{TYPE} =~ /^.pty.$/ ) {
  2562.            $_->{TFD} = $self->{PTYS}->{$_->{PTY_ID}}->fileno;
  2563.            $needed[$_->{TFD}] = 1;
  2564.         }
  2565.  
  2566. #        for ( $_->{FD}, ( $sibling != $kid ? $_->{TFD} : () ) ) {
  2567. #           if ( defined $_ && ! $closed[$_] && ! $needed[$_] ) {
  2568. #          _close( $_ );
  2569. #          $closed[$_] = 1;
  2570. #          $_ = undef;
  2571. #           }
  2572. #        }
  2573.      }
  2574.       }
  2575.  
  2576.       ## This is crude: we have no way of keeping track of browsing all open
  2577.       ## fds, so we scan to a fairly high fd.
  2578.       _debug "open fds: ", join " ", keys %fds if _debugging_details;
  2579.       for (keys %fds) {
  2580.          if ( ! $closed[$_] && ! $needed[$_] ) {
  2581.             _close( $_ );
  2582.             $closed[$_] = 1;
  2583.          }
  2584.       }
  2585.  
  2586.       ## Lazy closing is so the same fd (ie the same TFD value) can be dup2'ed on
  2587.       ## several times.
  2588.       my @lazy_close;
  2589.       for ( @{$kid->{OPS}} ) {
  2590.      if ( defined $_->{TFD} ) {
  2591.         unless ( $_->{TFD} == $_->{KFD} ) {
  2592.            $self->_dup2_gently( $kid->{OPS}, $_->{TFD}, $_->{KFD} );
  2593.            push @lazy_close, $_->{TFD};
  2594.         }
  2595.      }
  2596.      elsif ( $_->{TYPE} eq 'dup' ) {
  2597.         $self->_dup2_gently( $kid->{OPS}, $_->{KFD1}, $_->{KFD2} )
  2598.            unless $_->{KFD1} == $_->{KFD2};
  2599.      }
  2600.      elsif ( $_->{TYPE} eq 'close' ) {
  2601.         for ( $_->{KFD} ) {
  2602.            if ( ! $closed[$_] ) {
  2603.           _close( $_ );
  2604.           $closed[$_] = 1;
  2605.           $_ = undef;
  2606.            }
  2607.         }
  2608.      }
  2609.      elsif ( $_->{TYPE} eq 'init' ) {
  2610.         $_->{SUB}->();
  2611.      }
  2612.       }
  2613.  
  2614.       for ( @lazy_close ) {
  2615.      unless ( $closed[$_] ) {
  2616.         _close( $_ );
  2617.         $closed[$_] = 1;
  2618.      }
  2619.       }
  2620.  
  2621.       if ( ref $kid->{VAL} ne 'CODE' ) {
  2622.      open $s1, ">&=$self->{SYNC_WRITER_FD}"
  2623.         or croak "$! setting filehandle to fd SYNC_WRITER_FD";
  2624.      fcntl $s1, F_SETFD, 1;
  2625.  
  2626.      if ( defined $self->{DEBUG_FD} ) {
  2627.         open $s2, ">&=$self->{DEBUG_FD}"
  2628.            or croak "$! setting filehandle to fd DEBUG_FD";
  2629.         fcntl $s2, F_SETFD, 1;
  2630.      }
  2631.  
  2632.      my @cmd = ( $kid->{PATH}, @{$kid->{VAL}}[1..$#{$kid->{VAL}}] );
  2633.      _debug 'execing ', join " ", map { /[\s\"]/ ? "'$_'" : $_ } @cmd
  2634.         if _debugging;
  2635.  
  2636.      die "exec failed: simulating exec() failure"
  2637.         if $self->{_simulate_exec_failure};
  2638.  
  2639.      _exec $kid->{PATH}, @{$kid->{VAL}}[1..$#{$kid->{VAL}}];
  2640.  
  2641.      croak "exec failed: $!";
  2642.       }
  2643.    };
  2644.    if ( $@ ) {
  2645.       _write $self->{SYNC_WRITER_FD}, $@;
  2646.       ## Avoid DESTROY.
  2647.       POSIX::exit 1;
  2648.    }
  2649.  
  2650.    ## We must be executing code in the child, otherwise exec() would have
  2651.    ## prevented us from being here.
  2652.    _close $self->{SYNC_WRITER_FD};
  2653.    _debug 'calling fork()ed CODE ref' if _debugging;
  2654.    POSIX::close $self->{DEBUG_FD}      if defined $self->{DEBUG_FD};
  2655.    ## TODO: Overload CORE::GLOBAL::exit...
  2656.    $kid->{VAL}->();
  2657.  
  2658.    ## There are bugs in perl closures up to and including 5.6.1
  2659.    ## that may keep this next line from having any effect, and it
  2660.    ## won't have any effect if our caller has kept a copy of it, but
  2661.    ## this may cause the closure to be cleaned up.  Maybe.
  2662.    $kid->{VAL} = undef;
  2663.  
  2664.    ## Use POSIX::exit to avoid global destruction, since this might
  2665.    ## cause DESTROY() to be called on objects created in the parent
  2666.    ## and thus cause double cleanup.  For instance, if DESTROY() unlinks
  2667.    ## a file in the child, we don't want the parent to suddenly miss
  2668.    ## it.
  2669.    POSIX::exit 0;
  2670. }
  2671.  
  2672. =pod
  2673.  
  2674. =item start
  2675.  
  2676.    $h = start(
  2677.       \@cmd, \$in, \$out, ...,
  2678.       timeout( 30, name => "process timeout" ),
  2679.       $stall_timeout = timeout( 10, name => "stall timeout"   ),
  2680.    );
  2681.  
  2682.    $h = start \@cmd, '<', \$in, '|', \@cmd2, ...;
  2683.  
  2684. start() accepts a harness or harness specification and returns a harness
  2685. after building all of the pipes and launching (via fork()/exec(), or, maybe
  2686. someday, spawn()) all the child processes.  It does not send or receive any
  2687. data on the pipes, see pump() and finish() for that.
  2688.  
  2689. You may call harness() and then pass it's result to start() if you like,
  2690. but you only need to if it helps you structure or tune your application.
  2691. If you do call harness(), you may skip start() and proceed directly to
  2692. pump.
  2693.  
  2694. start() also starts all timers in the harness.  See L<IPC::Run::Timer>
  2695. for more information.
  2696.  
  2697. start() flushes STDOUT and STDERR to help you avoid duplicate output.
  2698. It has no way of asking Perl to flush all your open filehandles, so
  2699. you are going to need to flush any others you have open.  Sorry.
  2700.  
  2701. Here's how if you don't want to alter the state of $| for your
  2702. filehandle:
  2703.  
  2704.    $ofh = select HANDLE; $of = $|; $| = 1; $| = $of; select $ofh;
  2705.  
  2706. If you don't mind leaving output unbuffered on HANDLE, you can do
  2707. the slightly shorter
  2708.  
  2709.    $ofh = select HANDLE; $| = 1; select $ofh;
  2710.  
  2711. Or, you can use IO::Handle's flush() method:
  2712.  
  2713.    use IO::Handle;
  2714.    flush HANDLE;
  2715.  
  2716. Perl needs the equivalent of C's fflush( (FILE *)NULL ).
  2717.  
  2718. =cut
  2719.  
  2720. sub start {
  2721. # $SIG{__DIE__} = sub { my $s = shift; Carp::cluck $s; die $s };
  2722.    my $options;
  2723.    if ( @_ && ref $_[-1] eq 'HASH' ) {
  2724.       $options = pop;
  2725.       require Data::Dumper;
  2726.       carp "Passing in options as a hash is deprecated:\n", Data::Dumper::Dumper( $options );
  2727.    }
  2728.  
  2729.    my IPC::Run $self;
  2730.    if ( @_ == 1 && UNIVERSAL::isa( $_[0], __PACKAGE__ ) ) {
  2731.       $self = shift;
  2732.       $self->{$_} = $options->{$_} for keys %$options;
  2733.    }
  2734.    else {
  2735.       $self = harness( @_, $options ? $options : () );
  2736.    }
  2737.  
  2738.    local $cur_self = $self;
  2739.  
  2740.    $self->kill_kill if $self->{STATE} == _started;
  2741.  
  2742.    _debug "** starting" if _debugging;
  2743.  
  2744.    $_->{RESULT} = undef for @{$self->{KIDS}};
  2745.  
  2746.    ## Assume we're not being called from &run.  It will correct our
  2747.    ## assumption if need be.  This affects whether &_select_loop clears
  2748.    ## input queues to '' when they're empty.
  2749.    $self->{clear_ins} = 1;
  2750.  
  2751.    IPC::Run::Win32Helper::optimize $self
  2752.        if Win32_MODE && $in_run;
  2753.  
  2754.    my @errs;
  2755.  
  2756.    for ( @{$self->{TIMERS}} ) {
  2757.       eval { $_->start };
  2758.       if ( $@ ) {
  2759.          push @errs, $@;
  2760.          _debug 'caught ', $@ if _debugging;
  2761.       }
  2762.    }
  2763.  
  2764.    eval { $self->_open_pipes };
  2765.    if ( $@ ) {
  2766.       push @errs, $@;
  2767.       _debug 'caught ', $@ if _debugging;
  2768.    }
  2769.  
  2770.    if ( ! @errs ) {
  2771.       ## This is a bit of a hack, we should do it for all open filehandles.
  2772.       ## Since there's no way I know of to enumerate open filehandles, we
  2773.       ## autoflush STDOUT and STDERR.  This is done so that the children don't
  2774.       ## inherit output buffers chock full o' redundant data.  It's really
  2775.       ## confusing to track that down.
  2776.       { my $ofh = select STDOUT; local $| = 1; select $ofh; }
  2777.       { my $ofh = select STDERR; local $| = 1; select $ofh; }
  2778.       for my $kid ( @{$self->{KIDS}} ) {
  2779.          $kid->{RESULT} = undef;
  2780.          _debug "child: ",
  2781.             ref( $kid->{VAL} ) eq "CODE"
  2782.             ? "CODE ref"
  2783.             : (
  2784.                "`",
  2785.                join( " ", map /[^\w.-]/ ? "'$_'" : $_, @{$kid->{VAL}} ),
  2786.                "`"
  2787.             ) if _debugging_details;
  2788.          eval {
  2789.             croak "simulated failure of fork"
  2790.                if $self->{_simulate_fork_failure};
  2791.             unless ( Win32_MODE ) {
  2792.            $self->_spawn( $kid );
  2793.             }
  2794.             else {
  2795. ## TODO: Test and debug spawing code.  Someday.
  2796.                _debug( 
  2797.                   'spawning ',
  2798.                   join(
  2799.                      ' ',
  2800.                      map(
  2801.                         "'$_'",
  2802.                         ( $kid->{PATH}, @{$kid->{VAL}}[1..$#{$kid->{VAL}}] )
  2803.                      )
  2804.                   )
  2805.                ) if _debugging;
  2806.            ## The external kid wouldn't know what to do with it anyway.
  2807.            ## This is only used by the "helper" pump processes on Win32.
  2808.            _dont_inherit( $self->{DEBUG_FD} );
  2809.                ( $kid->{PID}, $kid->{PROCESS} ) =
  2810.           IPC::Run::Win32Helper::win32_spawn( 
  2811.              [ $kid->{PATH}, @{$kid->{VAL}}[1..$#{$kid->{VAL}}] ],
  2812.              $kid->{OPS},
  2813.           );
  2814.                _debug "spawn() = ", $kid->{PID} if _debugging;
  2815.             }
  2816.          };
  2817.          if ( $@ ) {
  2818.             push @errs, $@;
  2819.             _debug 'caught ', $@ if _debugging;
  2820.          }
  2821.       }
  2822.    }
  2823.  
  2824.    ## Close all those temporary filehandles that the kids needed.
  2825.    for my $pty ( values %{$self->{PTYS}} ) {
  2826.       close $pty->slave;
  2827.    }
  2828.  
  2829.    my @closed;
  2830.    for my $kid ( @{$self->{KIDS}} ) {
  2831.       for ( @{$kid->{OPS}} ) {
  2832.          my $close_it = eval {
  2833.             defined $_->{TFD}
  2834.                && ! $_->{DONT_CLOSE}
  2835.                && ! $closed[$_->{TFD}]
  2836.                && ( ! Win32_MODE || ! $_->{RECV_THROUGH_TEMP_FILE} ) ## Win32 hack
  2837.          };
  2838.          if ( $@ ) {
  2839.             push @errs, $@;
  2840.             _debug 'caught ', $@ if _debugging;
  2841.          }
  2842.          if ( $close_it || $@ ) {
  2843.             eval {
  2844.                _close( $_->{TFD} );
  2845.                $closed[$_->{TFD}] = 1;
  2846.                $_->{TFD} = undef;
  2847.             };
  2848.             if ( $@ ) {
  2849.                push @errs, $@;
  2850.                _debug 'caught ', $@ if _debugging;
  2851.             }
  2852.          }
  2853.       }
  2854.    }
  2855. confess "gak!" unless defined $self->{PIPES};
  2856.  
  2857.    if ( @errs ) {
  2858.       eval { $self->_cleanup };
  2859.       warn $@ if $@;
  2860.       die join( '', @errs );
  2861.    }
  2862.  
  2863.    $self->{STATE} = _started;
  2864.    return $self;
  2865. }
  2866.  
  2867. =item adopt
  2868.  
  2869. Experimental feature. NOT FUNCTIONAL YET, NEED TO CLOSE FDS BETTER IN CHILDREN.  SEE t/adopt.t for a test suite.
  2870.  
  2871. =cut
  2872.  
  2873. sub adopt {
  2874.    my IPC::Run $self = shift;
  2875.  
  2876.    for my $adoptee ( @_ ) {
  2877.       push @{$self->{IOS}},    @{$adoptee->{IOS}};
  2878.       ## NEED TO RENUMBER THE KIDS!!
  2879.       push @{$self->{KIDS}},   @{$adoptee->{KIDS}};
  2880.       push @{$self->{PIPES}},  @{$adoptee->{PIPES}};
  2881.       $self->{PTYS}->{$_} = $adoptee->{PTYS}->{$_}
  2882.          for keys %{$adoptee->{PYTS}};
  2883.       push @{$self->{TIMERS}}, @{$adoptee->{TIMERS}};
  2884.       $adoptee->{STATE} = _finished;
  2885.    }
  2886. }
  2887.  
  2888.  
  2889. sub _clobber {
  2890.    my IPC::Run $self = shift;
  2891.    my ( $file ) = @_;
  2892.    _debug_desc_fd( "closing", $file ) if _debugging_details;
  2893.    my $doomed = $file->{FD};
  2894.    my $dir = $file->{TYPE} =~ /^</ ? 'WIN' : 'RIN';
  2895.    vec( $self->{$dir}, $doomed, 1 ) = 0;
  2896. #   vec( $self->{EIN},  $doomed, 1 ) = 0;
  2897.    vec( $self->{PIN},  $doomed, 1 ) = 0;
  2898.    if ( $file->{TYPE} =~ /^(.)pty.$/ ) {
  2899.       if ( $1 eq '>' ) {
  2900.          ## Only close output ptys.  This is so that ptys as inputs are
  2901.          ## never autoclosed, which would risk losing data that was
  2902.          ## in the slave->parent queue.
  2903.          _debug_desc_fd "closing pty", $file if _debugging_details;
  2904.          close $self->{PTYS}->{$file->{PTY_ID}}
  2905.             if defined $self->{PTYS}->{$file->{PTY_ID}};
  2906.          $self->{PTYS}->{$file->{PTY_ID}} = undef;
  2907.       }
  2908.    }
  2909.    elsif ( UNIVERSAL::isa( $file, 'IPC::Run::IO' ) ) {
  2910.       $file->close unless $file->{DONT_CLOSE};
  2911.    }
  2912.    else {
  2913.       _close( $doomed );
  2914.    }
  2915.  
  2916.    @{$self->{PIPES}} = grep
  2917.       defined $_->{FD} && ( $_->{TYPE} ne $file->{TYPE} || $_->{FD} ne $doomed),
  2918.       @{$self->{PIPES}};
  2919.  
  2920.    $file->{FD} = undef;
  2921. }
  2922.  
  2923. sub _select_loop {
  2924.    my IPC::Run $self = shift;
  2925.  
  2926.    my $io_occurred;
  2927.  
  2928.    my $not_forever = 0.01;
  2929.  
  2930. SELECT:
  2931.    while ( $self->pumpable ) {
  2932.       if ( $io_occurred && $self->{break_on_io} ) {
  2933.          _debug "exiting _select(): io occured and break_on_io set"
  2934.         if _debugging_details;
  2935.          last;
  2936.       }
  2937.  
  2938.       my $timeout = $self->{non_blocking} ? 0 : undef;
  2939.  
  2940.       if ( @{$self->{TIMERS}} ) {
  2941.          my $now = time;
  2942.          my $time_left;
  2943.          for ( @{$self->{TIMERS}} ) {
  2944.             next unless $_->is_running;
  2945.             $time_left = $_->check( $now );
  2946.             ## Return when a timer expires
  2947.             return if defined $time_left && ! $time_left;
  2948.             $timeout = $time_left
  2949.                if ! defined $timeout || $time_left < $timeout;
  2950.          }
  2951.       }
  2952.  
  2953.       ##
  2954.       ## See if we can unpause any input channels
  2955.       ##
  2956.       my $paused = 0;
  2957.  
  2958.       for my $file ( @{$self->{PIPES}} ) {
  2959.          next unless $file->{PAUSED} && $file->{TYPE} =~ /^</;
  2960.  
  2961.          _debug_desc_fd( "checking for more input", $file ) if _debugging_details;
  2962.          my $did;
  2963.          1 while $did = $file->_do_filters( $self );
  2964.          if ( defined $file->{FD} && ! defined( $did ) || $did ) {
  2965.             _debug_desc_fd( "unpausing", $file ) if _debugging_details;
  2966.             $file->{PAUSED} = 0;
  2967.             vec( $self->{WIN}, $file->{FD}, 1 ) = 1;
  2968. #        vec( $self->{EIN}, $file->{FD}, 1 ) = 1;
  2969.             vec( $self->{PIN}, $file->{FD}, 1 ) = 0;
  2970.          }
  2971.          else {
  2972.             ## This gets incremented occasionally when the IO channel
  2973.             ## was actually closed.  That's a bug, but it seems mostly
  2974.             ## harmless: it causes us to exit if break_on_io, or to set
  2975.             ## the timeout to not be forever.  I need to fix it, though.
  2976.             ++$paused;
  2977.          }
  2978.       }
  2979.  
  2980.       if ( _debugging_details ) {
  2981.          my $map = join(
  2982.             '',
  2983.             map {
  2984.                my $out;
  2985.                $out = 'r'                     if vec( $self->{RIN}, $_, 1 );
  2986.                $out = $out ? 'b' : 'w'        if vec( $self->{WIN}, $_, 1 );
  2987.                $out = 'p'           if ! $out && vec( $self->{PIN}, $_, 1 );
  2988.                $out = $out ? uc( $out ) : 'x' if vec( $self->{EIN}, $_, 1 );
  2989.                $out = '-' unless $out;
  2990.                $out;
  2991.             } (0..1024)
  2992.          );
  2993.          $map =~ s/((?:[a-zA-Z-]|\([^\)]*\)){12,}?)-*$/$1/;
  2994.          _debug 'fds for select: ', $map if _debugging_details;
  2995.       }
  2996.  
  2997.       ## _do_filters may have closed our last fd, and we need to see if
  2998.       ## we have I/O, or are just waiting for children to exit.
  2999.       my $p = $self->pumpable;
  3000.       last unless $p;
  3001.       if ( $p > 0  && ( ! defined $timeout || $timeout > 0.1 ) ) {
  3002.          ## No I/O will wake the select loop up, but we have children
  3003.          ## lingering, so we need to poll them with a short timeout.
  3004.      ## Otherwise, assume more input will be coming.
  3005.      $timeout = $not_forever;
  3006.          $not_forever *= 2;
  3007.          $not_forever = 0.5 if $not_forever >= 0.5;
  3008.       }
  3009.  
  3010.       ## Make sure we don't block forever in select() because inputs are
  3011.       ## paused.
  3012.       if ( ! defined $timeout && ! ( @{$self->{PIPES}} - $paused ) ) {
  3013.          ## Need to return if we're in pump and all input is paused, or
  3014.      ## we'll loop until all inputs are unpaused, which is darn near
  3015.      ## forever.  And a day.
  3016.          if ( $self->{break_on_io} ) {
  3017.         _debug "exiting _select(): no I/O to do and timeout=forever"
  3018.                if _debugging;
  3019.         last;
  3020.      }
  3021.  
  3022.      ## Otherwise, assume more input will be coming.
  3023.      $timeout = $not_forever;
  3024.          $not_forever *= 2;
  3025.          $not_forever = 0.5 if $not_forever >= 0.5;
  3026.       }
  3027.  
  3028.       _debug 'timeout=', defined $timeout ? $timeout : 'forever'
  3029.          if _debugging_details;
  3030.  
  3031.       my $nfound;
  3032.       unless ( Win32_MODE ) {
  3033.          $nfound = select(
  3034.             $self->{ROUT} = $self->{RIN},
  3035.             $self->{WOUT} = $self->{WIN},
  3036.             $self->{EOUT} = $self->{EIN},
  3037.             $timeout 
  3038.      );
  3039.       }
  3040.       else {
  3041.      my @in = map $self->{$_}, qw( RIN WIN EIN );
  3042.      ## Win32's select() on Win32 seems to die if passed vectors of
  3043.      ## all 0's.  Need to report this when I get back online.
  3044.      for ( @in ) {
  3045.         $_ = undef unless index( ( unpack "b*", $_ ), 1 ) >= 0;
  3046.      }
  3047.  
  3048.      $nfound = select(
  3049.             $self->{ROUT} = $in[0],
  3050.             $self->{WOUT} = $in[1],
  3051.             $self->{EOUT} = $in[2],
  3052.             $timeout 
  3053.          );
  3054.  
  3055.      for ( $self->{ROUT}, $self->{WOUT}, $self->{EOUT} ) {
  3056.         $_ = "" unless defined $_;
  3057.      }
  3058.       }
  3059.       last if ! $nfound && $self->{non_blocking};
  3060.  
  3061.       croak "$! in select" if $nfound < 0 and $! != POSIX::EINTR;
  3062.           ## TODO: Analyze the EINTR failure mode and see if this patch
  3063.           ## is adequate and optimal.
  3064.           ## TODO: Add an EINTR test to the test suite.
  3065.  
  3066.       if ( _debugging_details ) {
  3067.          my $map = join(
  3068.             '',
  3069.             map {
  3070.                my $out;
  3071.                $out = 'r'                     if vec( $self->{ROUT}, $_, 1 );
  3072.                $out = $out ? 'b' : 'w'        if vec( $self->{WOUT}, $_, 1 );
  3073.                $out = $out ? uc( $out ) : 'x' if vec( $self->{EOUT}, $_, 1 );
  3074.                $out = '-' unless $out;
  3075.                $out;
  3076.             } (0..128)
  3077.          );
  3078.          $map =~ s/((?:[a-zA-Z-]|\([^\)]*\)){12,}?)-*$/$1/;
  3079.          _debug "selected  ", $map;
  3080.       }
  3081.  
  3082.       ## Need to copy since _clobber alters @{$self->{PIPES}}.
  3083.       ## TODO: Rethink _clobber().  Rethink $file->{PAUSED}, too.
  3084.       my @pipes = @{$self->{PIPES}};
  3085.       $io_occurred = $_->poll( $self ) ? 1 : $io_occurred for @pipes;
  3086. #   FILE:
  3087. #      for my $pipe ( @pipes ) {
  3088. #         ## Pipes can be shared among kids.  If another kid closes the
  3089. #         ## pipe, then it's {FD} will be undef.  Also, on Win32, pipes can
  3090. #     ## be optimized to be files, in which case the FD is left undef
  3091. #     ## so we don't try to select() on it.
  3092. #         if ( $pipe->{TYPE} =~ /^>/
  3093. #            && defined $pipe->{FD}
  3094. #            && vec( $self->{ROUT}, $pipe->{FD}, 1 )
  3095. #         ) {
  3096. #            _debug_desc_fd( "filtering data from", $pipe ) if _debugging_details;
  3097. #confess "phooey" unless UNIVERSAL::isa( $pipe, "IPC::Run::IO" );
  3098. #            $io_occurred = 1 if $pipe->_do_filters( $self );
  3099. #
  3100. #            next FILE unless defined $pipe->{FD};
  3101. #         }
  3102. #
  3103. #     ## On Win32, pipes to the child can be optimized to be files
  3104. #     ## and FD left undefined so we won't select on it.
  3105. #         if ( $pipe->{TYPE} =~ /^</
  3106. #            && defined $pipe->{FD}
  3107. #            && vec( $self->{WOUT}, $pipe->{FD}, 1 )
  3108. #         ) {
  3109. #            _debug_desc_fd( "filtering data to", $pipe ) if _debugging_details;
  3110. #            $io_occurred = 1 if $pipe->_do_filters( $self );
  3111. #
  3112. #            next FILE unless defined $pipe->{FD};
  3113. #         }
  3114. #
  3115. #         if ( defined $pipe->{FD} && vec( $self->{EOUT}, $pipe->{FD}, 1 ) ) {
  3116. #            ## BSD seems to sometimes raise the exceptional condition flag
  3117. #            ## when a pipe is closed before we read it's last data.  This
  3118. #            ## causes spurious warnings and generally renders the exception
  3119. #            ## mechanism useless for our purposes.  The exception
  3120. #            ## flag semantics are too variable (they're device driver
  3121. #            ## specific) for me to easily map to any automatic action like
  3122. #            ## warning or croaking (try running v0.42 if you don't beleive me
  3123. #            ## :-).
  3124. #            warn "Exception on descriptor $pipe->{FD}";
  3125. #         }
  3126. #      }
  3127.    }
  3128.  
  3129.    return;
  3130. }
  3131.  
  3132.  
  3133. sub _cleanup {
  3134.    my IPC::Run $self = shift;
  3135.    _debug "cleaning up" if _debugging_details;
  3136.  
  3137.    for ( values %{$self->{PTYS}} ) {
  3138.       next unless ref $_;
  3139.       eval {
  3140.          _debug "closing slave fd ", fileno $_->slave if _debugging_data;
  3141.          close $_->slave;
  3142.       };
  3143.       carp $@ . " while closing ptys" if $@;
  3144.       eval {
  3145.          _debug "closing master fd ", fileno $_ if _debugging_data;
  3146.          close $_;
  3147.       };
  3148.       carp $@ . " closing ptys" if $@;
  3149.    }
  3150.    
  3151.    _debug "cleaning up pipes" if _debugging_details;
  3152.    ## _clobber modifies PIPES
  3153.    $self->_clobber( $self->{PIPES}->[0] ) while @{$self->{PIPES}};
  3154.  
  3155.    for my $kid ( @{$self->{KIDS}} ) {
  3156.       _debug "cleaning up kid ", $kid->{NUM} if _debugging_details;
  3157.       if ( ! length $kid->{PID} ) {
  3158.          _debug 'never ran child ', $kid->{NUM}, ", can't reap"
  3159.             if _debugging;
  3160.          for my $op ( @{$kid->{OPS}} ) {
  3161.             _close( $op->{TFD} )
  3162.                if defined $op->{TFD} && ! defined $op->{TEMP_FILE_HANDLE};
  3163.          }
  3164.       }
  3165.       elsif ( ! defined $kid->{RESULT} ) {
  3166.          _debug 'reaping child ', $kid->{NUM}, ' (pid ', $kid->{PID}, ')'
  3167.             if _debugging;
  3168.          my $pid = waitpid $kid->{PID}, 0;
  3169.          $kid->{RESULT} = $?;
  3170.          _debug 'reaped ', $pid, ', $?=', $kid->{RESULT}
  3171.             if _debugging;
  3172.       }
  3173.  
  3174. #      if ( defined $kid->{DEBUG_FD} ) {
  3175. #     die;
  3176. #         @{$kid->{OPS}} = grep
  3177. #            ! defined $_->{KFD} || $_->{KFD} != $kid->{DEBUG_FD},
  3178. #            @{$kid->{OPS}};
  3179. #         $kid->{DEBUG_FD} = undef;
  3180. #      }
  3181.  
  3182.       _debug "cleaning up filters" if _debugging_details;
  3183.       for my $op ( @{$kid->{OPS}} ) {
  3184.          @{$op->{FILTERS}} = grep {
  3185.             my $filter = $_;
  3186.             ! grep $filter == $_, @{$self->{TEMP_FILTERS}};
  3187.          } @{$op->{FILTERS}};
  3188.       }
  3189.  
  3190.       for my $op ( @{$kid->{OPS}} ) {
  3191.          $op->_cleanup( $self ) if UNIVERSAL::isa( $op, "IPC::Run::IO" );
  3192.       }
  3193.    }
  3194.    $self->{STATE} = _finished;
  3195.    @{$self->{TEMP_FILTERS}} = ();
  3196.    _debug "done cleaning up" if _debugging_details;
  3197.  
  3198.    POSIX::close $self->{DEBUG_FD} if defined $self->{DEBUG_FD};
  3199.    $self->{DEBUG_FD} = undef;
  3200. }
  3201.  
  3202. =pod
  3203.  
  3204. =item pump
  3205.  
  3206.    pump $h;
  3207.    $h->pump;
  3208.  
  3209. Pump accepts a single parameter harness.  It blocks until it delivers some
  3210. input or recieves some output.  It returns TRUE if there is still input or
  3211. output to be done, FALSE otherwise.
  3212.  
  3213. pump() will automatically call start() if need be, so you may call harness()
  3214. then proceed to pump() if that helps you structure your application.
  3215.  
  3216. If pump() is called after all harnessed activities have completed, a "process
  3217. ended prematurely" exception to be thrown.  This allows for simple scripting
  3218. of external applications without having to add lots of error handling code at
  3219. each step of the script:
  3220.  
  3221.    $h = harness \@smbclient, \$in, \$out, $err;
  3222.  
  3223.    $in = "cd /foo\n";
  3224.    $h->pump until $out =~ /^smb.*> \Z/m;
  3225.    die "error cding to /foo:\n$out" if $out =~ "ERR";
  3226.    $out = '';
  3227.  
  3228.    $in = "mget *\n";
  3229.    $h->pump until $out =~ /^smb.*> \Z/m;
  3230.    die "error retrieving files:\n$out" if $out =~ "ERR";
  3231.  
  3232.    $h->finish;
  3233.  
  3234.    warn $err if $err;
  3235.  
  3236. =cut
  3237.  
  3238. sub pump {
  3239.    die "pump() takes only a a single harness as a parameter"
  3240.       unless @_ == 1 && UNIVERSAL::isa( $_[0], __PACKAGE__ );
  3241.  
  3242.    my IPC::Run $self = shift;
  3243.  
  3244.    local $cur_self = $self;
  3245.  
  3246.    _debug "** pumping" 
  3247.       if _debugging;
  3248.  
  3249. #   my $r = eval {
  3250.       $self->start if $self->{STATE} < _started;
  3251.       croak "process ended prematurely" unless $self->pumpable;
  3252.  
  3253.       $self->{auto_close_ins} = 0;
  3254.       $self->{break_on_io}    = 1;
  3255.       $self->_select_loop;
  3256.       return $self->pumpable;
  3257. #   };
  3258. #   if ( $@ ) {
  3259. #      my $x = $@;
  3260. #      _debug $x if _debugging && $x;
  3261. #      eval { $self->_cleanup };
  3262. #      warn $@ if $@;
  3263. #      die $x;
  3264. #   }
  3265. #   return $r;
  3266. }
  3267.  
  3268. =pod
  3269.  
  3270. =item pump_nb
  3271.  
  3272.    pump_nb $h;
  3273.    $h->pump_nb;
  3274.  
  3275. "pump() non-blocking", pumps if anything's ready to be pumped, returns
  3276. immediately otherwise.  This is useful if you're doing some long-running
  3277. task in the foreground, but don't want to starve any child processes.
  3278.  
  3279. =cut
  3280.  
  3281. sub pump_nb {
  3282.    my IPC::Run $self = shift;
  3283.  
  3284.    $self->{non_blocking} = 1;
  3285.    my $r = eval { $self->pump };
  3286.    $self->{non_blocking} = 0;
  3287.    die $@ if $@;
  3288.    return $r;
  3289. }
  3290.  
  3291. =pod
  3292.  
  3293. =item pumpable
  3294.  
  3295. Returns TRUE if calling pump() won't throw an immediate "process ended
  3296. prematurely" exception.  This means that there are open I/O channels or
  3297. active processes. May yield the parent processes' time slice for 0.01
  3298. second if all pipes are to the child and all are paused.  In this case
  3299. we can't tell if the child is dead, so we yield the processor and
  3300. then attempt to reap the child in a nonblocking way.
  3301.  
  3302. =cut
  3303.  
  3304. ## Undocumented feature (don't depend on it outside this module):
  3305. ## returns -1 if we have I/O channels open, or >0 if no I/O channels
  3306. ## open, but we have kids running.  This allows the select loop
  3307. ## to poll for child exit.
  3308. sub pumpable {
  3309.    my IPC::Run $self = shift;
  3310.  
  3311.    ## There's a catch-22 we can get in to if there is only one pipe left
  3312.    ## open to the child and it's paused (ie the SCALAR it's tied to
  3313.    ## is '').  It's paused, so we're not select()ing on it, so we don't
  3314.    ## check it to see if the child attached to it is alive and it stays
  3315.    ## in @{$self->{PIPES}} forever.  So, if all pipes are paused, see if
  3316.    ## we can reap the child.
  3317.    return -1 if grep !$_->{PAUSED}, @{$self->{PIPES}};
  3318.  
  3319.    ## See if the child is dead.
  3320.    $self->reap_nb;
  3321.    return 0 unless $self->_running_kids;
  3322.  
  3323.    ## If we reap_nb and it's not dead yet, yield to it to see if it
  3324.    ## exits.
  3325.    ##
  3326.    ## A better solution would be to unpause all the pipes, but I tried that
  3327.    ## and it never errored on linux.  Sigh.  
  3328.    select undef, undef, undef, 0.0001;
  3329.  
  3330.    ## try again
  3331.    $self->reap_nb;
  3332.    return 0 unless $self->_running_kids;
  3333.  
  3334.    return -1; ## There are pipes waiting
  3335. }
  3336.  
  3337.  
  3338. sub _running_kids {
  3339.    my IPC::Run $self = shift;
  3340.    return grep
  3341.       defined $_->{PID} && ! defined $_->{RESULT},
  3342.       @{$self->{KIDS}};
  3343. }
  3344.  
  3345. =pod
  3346.  
  3347. =item reap_nb
  3348.  
  3349. Attempts to reap child processes, but does not block.
  3350.  
  3351. Does not currently take any parameters, one day it will allow specific
  3352. children to be reaped.
  3353.  
  3354. Only call this from a signal handler if your C<perl> is recent enough
  3355. to have safe signal handling (5.6.1 did not, IIRC, but it was beign discussed
  3356. on perl5-porters).  Calling this (or doing any significant work) in a signal
  3357. handler on older C<perl>s is asking for seg faults.
  3358.  
  3359. =cut
  3360.  
  3361. my $still_runnings;
  3362.  
  3363. sub reap_nb {
  3364.    my IPC::Run $self = shift;
  3365.  
  3366.    local $cur_self = $self;
  3367.  
  3368.    ## No more pipes, look to see if all the kids yet live, reaping those
  3369.    ## that haven't.  I'd use $SIG{CHLD}/$SIG{CLD}, but that's broken
  3370.    ## on older (SYSV) platforms and perhaps less portable than waitpid().
  3371.    ## This could be slow with a lot of kids, but that's rare and, well,
  3372.    ## a lot of kids is slow in the first place.
  3373.    ## Oh, and this keeps us from reaping other children the process
  3374.    ## may have spawned.
  3375.    for my $kid ( @{$self->{KIDS}} ) {
  3376.       if ( Win32_MODE ) {
  3377.      next if ! defined $kid->{PROCESS} || defined $kid->{RESULT};
  3378.      unless ( $kid->{PROCESS}->Wait( 0 ) ) {
  3379.         _debug "kid $kid->{NUM} ($kid->{PID}) still running"
  3380.                if _debugging_details;
  3381.         next;
  3382.      }
  3383.  
  3384.          _debug "kid $kid->{NUM} ($kid->{PID}) exited"
  3385.             if _debugging;
  3386.  
  3387.      $kid->{PROCESS}->GetExitCode( $kid->{RESULT} )
  3388.         or croak "$! while GetExitCode()ing for Win32 process";
  3389.  
  3390.      unless ( defined $kid->{RESULT} ) {
  3391.         $kid->{RESULT} = "0 but true";
  3392.         $? = $kid->{RESULT} = 0x0F;
  3393.      }
  3394.      else {
  3395.         $? = $kid->{RESULT} << 8;
  3396.      }
  3397.       }
  3398.       else {
  3399.      next if ! defined $kid->{PID} || defined $kid->{RESULT};
  3400.      my $pid = waitpid $kid->{PID}, POSIX::WNOHANG();
  3401.      unless ( $pid ) {
  3402.         _debug "$kid->{NUM} ($kid->{PID}) still running"
  3403.                if _debugging_details;
  3404.         next;
  3405.      }
  3406.  
  3407.      if ( $pid < 0 ) {
  3408.         _debug "No such process: $kid->{PID}\n" if _debugging;
  3409.         $kid->{RESULT} = "unknown result, unknown PID";
  3410.      }
  3411.      else {
  3412.             _debug "kid $kid->{NUM} ($kid->{PID}) exited"
  3413.                if _debugging;
  3414.  
  3415.         confess "waitpid returned the wrong PID: $pid instead of $kid->{PID}"
  3416.            unless $pid = $kid->{PID};
  3417.         _debug "$kid->{PID} returned $?\n" if _debugging;
  3418.         $kid->{RESULT} = $?;
  3419.      }
  3420.       }
  3421.    }
  3422. }
  3423.  
  3424. =pod
  3425.  
  3426. =item finish
  3427.  
  3428. This must be called after the last start() or pump() call for a harness,
  3429. or your system will accumulate defunct processes and you may "leak"
  3430. file descriptors.
  3431.  
  3432. finish() returns TRUE if all children returned 0 (and were not signaled and did
  3433. not coredump, ie ! $?), and FALSE otherwise (this is like run(), and the
  3434. opposite of system()).
  3435.  
  3436. Once a harness has been finished, it may be run() or start()ed again,
  3437. including by pump()s auto-start.
  3438.  
  3439. If this throws an exception rather than a normal exit, the harness may
  3440. be left in an unstable state, it's best to kill the harness to get rid
  3441. of all the child processes, etc.
  3442.  
  3443. Specifically, if a timeout expires in finish(), finish() will not
  3444. kill all the children.  Call C<<$h->kill_kill>> in this case if you care.
  3445. This differs from the behavior of L</run>.
  3446.  
  3447. =cut
  3448.  
  3449. sub finish {
  3450.    my IPC::Run $self = shift;
  3451.    my $options = @_ && ref $_[-1] eq 'HASH' ? pop : {};
  3452.  
  3453.    local $cur_self = $self;
  3454.  
  3455.    _debug "** finishing" if _debugging;
  3456.  
  3457.    $self->{non_blocking}   = 0;
  3458.    $self->{auto_close_ins} = 1;
  3459.    $self->{break_on_io}    = 0;
  3460.    # We don't alter $self->{clear_ins}, start() and run() control it.
  3461.  
  3462.    while ( $self->pumpable ) {
  3463.       $self->_select_loop( $options );
  3464.    }
  3465.    $self->_cleanup;
  3466.  
  3467.    return ! $self->full_result;
  3468. }
  3469.  
  3470. =pod
  3471.  
  3472. =item result
  3473.  
  3474.    $h->result;
  3475.  
  3476. Returns the first non-zero result code (ie $? >> 8).  See L</full_result> to 
  3477. get the $? value for a child process.
  3478.  
  3479. To get the result of a particular child, do:
  3480.  
  3481.    $h->result( 0 );  # first child's $? >> 8
  3482.    $h->result( 1 );  # second child
  3483.  
  3484. or
  3485.  
  3486.    ($h->results)[0]
  3487.    ($h->results)[1]
  3488.  
  3489. Returns undef if no child processes were spawned and no child number was
  3490. specified.  Throws an exception if an out-of-range child number is passed.
  3491.  
  3492. =cut
  3493.  
  3494. sub _assert_finished {
  3495.    my IPC::Run $self = $_[0];
  3496.  
  3497.    croak "Harness not run" unless $self->{STATE} >= _finished;
  3498.    croak "Harness not finished running" unless $self->{STATE} == _finished;
  3499. }
  3500.  
  3501.  
  3502. sub result {
  3503.    &_assert_finished;
  3504.    my IPC::Run $self = shift;
  3505.    
  3506.    if ( @_ ) {
  3507.       my ( $which ) = @_;
  3508.       croak(
  3509.          "Only ",
  3510.          scalar( @{$self->{KIDS}} ),
  3511.          " child processes, no process $which"
  3512.       )
  3513.          unless $which >= 0 && $which <= $#{$self->{KIDS}};
  3514.       return $self->{KIDS}->[$which]->{RESULT} >> 8;
  3515.    }
  3516.    else {
  3517.       return undef unless @{$self->{KIDS}};
  3518.       for ( @{$self->{KIDS}} ) {
  3519.          return $_->{RESULT} >> 8 if $_->{RESULT} >> 8;
  3520.       }
  3521.    }
  3522. }
  3523.  
  3524. =pod
  3525.  
  3526. =item results
  3527.  
  3528. Returns a list of child exit values.  See L</full_results> if you want to
  3529. know if a signal killed the child.
  3530.  
  3531. Throws an exception if the harness is not in a finished state.
  3532.  
  3533. =cut
  3534.  
  3535. sub results {
  3536.    &_assert_finished;
  3537.    my IPC::Run $self = shift;
  3538.  
  3539.    # we add 0 here to stop warnings associated with "unknown result, unknown PID"
  3540.    return map { (0+$_->{RESULT}) >> 8 } @{$self->{KIDS}};
  3541. }
  3542.  
  3543. =pod
  3544.  
  3545. =item full_result
  3546.  
  3547.    $h->full_result;
  3548.  
  3549. Returns the first non-zero $?.  See L</result> to get the first $? >> 8 
  3550. value for a child process.
  3551.  
  3552. To get the result of a particular child, do:
  3553.  
  3554.    $h->full_result( 0 );  # first child's $? >> 8
  3555.    $h->full_result( 1 );  # second child
  3556.  
  3557. or
  3558.  
  3559.    ($h->full_results)[0]
  3560.    ($h->full_results)[1]
  3561.  
  3562. Returns undef if no child processes were spawned and no child number was
  3563. specified.  Throws an exception if an out-of-range child number is passed.
  3564.  
  3565. =cut
  3566.  
  3567. sub full_result {
  3568.    goto &result if @_ > 1;
  3569.    &_assert_finished;
  3570.  
  3571.    my IPC::Run $self = shift;
  3572.  
  3573.    return undef unless @{$self->{KIDS}};
  3574.    for ( @{$self->{KIDS}} ) {
  3575.       return $_->{RESULT} if $_->{RESULT};
  3576.    }
  3577. }
  3578.  
  3579. =pod
  3580.  
  3581. =item full_results
  3582.  
  3583. Returns a list of child exit values as returned by C<wait>.  See L</results>
  3584. if you don't care about coredumps or signals.
  3585.  
  3586. Throws an exception if the harness is not in a finished state.
  3587.  
  3588. =cut
  3589.  
  3590. sub full_results {
  3591.    &_assert_finished;
  3592.    my IPC::Run $self = shift;
  3593.  
  3594.    croak "Harness not run" unless $self->{STATE} >= _finished;
  3595.    croak "Harness not finished running" unless $self->{STATE} == _finished;
  3596.  
  3597.    return map $_->{RESULT}, @{$self->{KIDS}};
  3598. }
  3599.  
  3600.  
  3601. ##
  3602. ## Filter Scaffolding
  3603. ##
  3604. use vars (
  3605.    '$filter_op',        ## The op running a filter chain right now
  3606.    '$filter_num',       ## Which filter is being run right now.
  3607. );
  3608.  
  3609. ##
  3610. ## A few filters and filter constructors
  3611. ##
  3612.  
  3613. =pod
  3614.  
  3615. =back
  3616.  
  3617. =back
  3618.  
  3619. =head1 FILTERS
  3620.  
  3621. These filters are used to modify input our output between a child
  3622. process and a scalar or subroutine endpoint.
  3623.  
  3624. =over
  3625.  
  3626. =item binary
  3627.  
  3628.    run \@cmd, ">", binary, \$out;
  3629.    run \@cmd, ">", binary, \$out;  ## Any TRUE value to enable
  3630.    run \@cmd, ">", binary 0, \$out;  ## Any FALSE value to disable
  3631.  
  3632. This is a constructor for a "binmode" "filter" that tells IPC::Run to keep
  3633. the carriage returns that would ordinarily be edited out for you (binmode
  3634. is usually off).  This is not a real filter, but an option masquerading as
  3635. a filter.
  3636.  
  3637. It's not named "binmode" because you're likely to want to call Perl's binmode
  3638. in programs that are piping binary data around.
  3639.  
  3640. =cut
  3641.  
  3642. sub binary(;$) {
  3643.    my $enable = @_ ? shift : 1;
  3644.    return bless sub { $enable }, "IPC::Run::binmode_pseudo_filter";
  3645. }
  3646.  
  3647. =pod
  3648.  
  3649. =item new_chunker
  3650.  
  3651. This breaks a stream of data in to chunks, based on an optional
  3652. scalar or regular expression parameter.  The default is the Perl
  3653. input record separator in $/, which is a newline be default.
  3654.  
  3655.    run \@cmd, '>', new_chunker, \&lines_handler;
  3656.    run \@cmd, '>', new_chunker( "\r\n" ), \&lines_handler;
  3657.  
  3658. Because this uses $/ by default, you should always pass in a parameter
  3659. if you are worried about other code (modules, etc) modifying $/.
  3660.  
  3661. If this filter is last in a filter chain that dumps in to a scalar,
  3662. the scalar must be set to '' before a new chunk will be written to it.
  3663.  
  3664. As an example of how a filter like this can be written, here's a
  3665. chunker that splits on newlines:
  3666.  
  3667.    sub line_splitter {
  3668.       my ( $in_ref, $out_ref ) = @_;
  3669.  
  3670.       return 0 if length $$out_ref;
  3671.  
  3672.       return input_avail && do {
  3673.          while (1) {
  3674.             if ( $$in_ref =~ s/\A(.*?\n)// ) {
  3675.                $$out_ref .= $1;
  3676.                return 1;
  3677.             }
  3678.             my $hmm = get_more_input;
  3679.             unless ( defined $hmm ) {
  3680.                $$out_ref = $$in_ref;
  3681.                $$in_ref = '';
  3682.                return length $$out_ref ? 1 : 0;
  3683.             }
  3684.             return 0 if $hmm eq 0;
  3685.          }
  3686.       }
  3687.    };
  3688.  
  3689. =cut
  3690.  
  3691. sub new_chunker(;$) {
  3692.    my ( $re ) = @_;
  3693.    $re = $/ if _empty $re;
  3694.    $re = quotemeta( $re ) unless ref $re eq 'Regexp';
  3695.    $re = qr/\A(.*?$re)/s;
  3696.  
  3697.    return sub {
  3698.       my ( $in_ref, $out_ref ) = @_;
  3699.  
  3700.       return 0 if length $$out_ref;
  3701.  
  3702.       return input_avail && do {
  3703.          while (1) {
  3704.             if ( $$in_ref =~ s/$re// ) {
  3705.                $$out_ref .= $1;
  3706.                return 1;
  3707.             }
  3708.             my $hmm = get_more_input;
  3709.             unless ( defined $hmm ) {
  3710.                $$out_ref = $$in_ref;
  3711.                $$in_ref = '';
  3712.                return length $$out_ref ? 1 : 0;
  3713.             }
  3714.             return 0 if $hmm eq 0;
  3715.          }
  3716.       }
  3717.    };
  3718. }
  3719.  
  3720. =pod
  3721.  
  3722. =item new_appender
  3723.  
  3724. This appends a fixed string to each chunk of data read from the source
  3725. scalar or sub.  This might be useful if you're writing commands to a
  3726. child process that always must end in a fixed string, like "\n":
  3727.  
  3728.    run( \@cmd,
  3729.       '<', new_appender( "\n" ), \&commands,
  3730.    );
  3731.  
  3732. Here's a typical filter sub that might be created by new_appender():
  3733.  
  3734.    sub newline_appender {
  3735.       my ( $in_ref, $out_ref ) = @_;
  3736.  
  3737.       return input_avail && do {
  3738.          $$out_ref = join( '', $$out_ref, $$in_ref, "\n" );
  3739.          $$in_ref = '';
  3740.          1;
  3741.       }
  3742.    };
  3743.  
  3744. =cut
  3745.  
  3746. sub new_appender($) {
  3747.    my ( $suffix ) = @_;
  3748.    croak "\$suffix undefined" unless defined $suffix;
  3749.  
  3750.    return sub {
  3751.       my ( $in_ref, $out_ref ) = @_;
  3752.  
  3753.       return input_avail && do {
  3754.          $$out_ref = join( '', $$out_ref, $$in_ref, $suffix );
  3755.          $$in_ref = '';
  3756.          1;
  3757.       }
  3758.    };
  3759. }
  3760.  
  3761. =item new_string_source
  3762.  
  3763. TODO: Needs confirmation. Was previously undocumented. in this module.
  3764.  
  3765. This is a filter which is exportable. Returns a sub which appends the data passed in to the output buffer and returns 1 if data was appended. 0 if it was an empty string and undef if no data was passed. 
  3766.  
  3767. NOTE: Any additional variables passed to new_string_source will be passed to the sub every time it's called and appended to the output. 
  3768.  
  3769. =cut
  3770.  
  3771.  
  3772. sub new_string_source {
  3773.    my $ref;
  3774.    if ( @_ > 1 ) {
  3775.       $ref = [ @_ ],
  3776.    }
  3777.    else {
  3778.       $ref = shift;
  3779.    }
  3780.  
  3781.    return ref $ref eq 'SCALAR'
  3782.       ? sub {
  3783.          my ( $in_ref, $out_ref ) = @_;
  3784.  
  3785.          return defined $$ref
  3786.             ? do {
  3787.                $$out_ref .= $$ref;
  3788.                my $r = length $$ref ? 1 : 0;
  3789.                $$ref = undef;
  3790.                $r;
  3791.             }
  3792.             : undef
  3793.       }
  3794.       : sub {
  3795.          my ( $in_ref, $out_ref ) = @_;
  3796.  
  3797.          return @$ref
  3798.             ? do {
  3799.                my $s = shift @$ref;
  3800.                $$out_ref .= $s;
  3801.                length $s ? 1 : 0;
  3802.             }
  3803.             : undef;
  3804.       }
  3805. }
  3806.  
  3807. =item new_string_sink
  3808.  
  3809. TODO: Needs confirmation. Was previously undocumented.
  3810.  
  3811. This is a filter which is exportable. Returns a sub which pops the data out of the input stream and pushes it onto the string.
  3812.  
  3813. =cut
  3814.  
  3815. sub new_string_sink {
  3816.    my ( $string_ref ) = @_;
  3817.  
  3818.    return sub {
  3819.       my ( $in_ref, $out_ref ) = @_;
  3820.  
  3821.       return input_avail && do {
  3822.          $$string_ref .= $$in_ref;
  3823.          $$in_ref = '';
  3824.          1;
  3825.       }
  3826.    };
  3827. }
  3828.  
  3829.  
  3830. #=item timeout
  3831. #
  3832. #This function defines a time interval, starting from when start() is
  3833. #called, or when timeout() is called.  If all processes have not finished
  3834. #by the end of the timeout period, then a "process timed out" exception
  3835. #is thrown.
  3836. #
  3837. #The time interval may be passed in seconds, or as an end time in
  3838. #"HH:MM:SS" format (any non-digit other than '.' may be used as
  3839. #spacing and puctuation).  This is probably best shown by example:
  3840. #
  3841. #   $h->timeout( $val );
  3842. #
  3843. #   $val                     Effect
  3844. #   ======================== =====================================
  3845. #   undef                    Timeout timer disabled
  3846. #   ''                       Almost immediate timeout
  3847. #   0                        Almost immediate timeout
  3848. #   0.000001                 timeout > 0.0000001 seconds
  3849. #   30                       timeout > 30 seconds
  3850. #   30.0000001               timeout > 30 seconds
  3851. #   10:30                    timeout > 10 minutes, 30 seconds
  3852. #
  3853. #Timeouts are currently evaluated with a 1 second resolution, though
  3854. #this may change in the future.  This means that setting
  3855. #timeout($h,1) will cause a pokey child to be aborted sometime after
  3856. #one second has elapsed and typically before two seconds have elapsed.
  3857. #
  3858. #This sub does not check whether or not the timeout has expired already.
  3859. #
  3860. #Returns the number of seconds set as the timeout (this does not change
  3861. #as time passes, unless you call timeout( val ) again).
  3862. #
  3863. #The timeout does not include the time needed to fork() or spawn()
  3864. #the child processes, though some setup time for the child processes can
  3865. #included.  It also does not include the length of time it takes for
  3866. #the children to exit after they've closed all their pipes to the
  3867. #parent process.
  3868. #
  3869. #=cut
  3870. #
  3871. #sub timeout {
  3872. #   my IPC::Run $self = shift;
  3873. #
  3874. #   if ( @_ ) {
  3875. #      ( $self->{TIMEOUT} ) = @_;
  3876. #      $self->{TIMEOUT_END} = undef;
  3877. #      if ( defined $self->{TIMEOUT} ) {
  3878. #     if ( $self->{TIMEOUT} =~ /[^\d.]/ ) {
  3879. #        my @f = split( /[^\d\.]+/i, $self->{TIMEOUT} );
  3880. #        unshift @f, 0 while @f < 3;
  3881. #        $self->{TIMEOUT} = (($f[0]*60)+$f[1])*60+$f[2];
  3882. #     }
  3883. #     elsif ( $self->{TIMEOUT} =~ /^(\d*)(?:\.(\d*))/ ) {
  3884. #        $self->{TIMEOUT} = $1 + 1;
  3885. #     }
  3886. #     $self->_calc_timeout_end if $self->{STATE} >= _started;
  3887. #      }
  3888. #   }
  3889. #   return $self->{TIMEOUT};
  3890. #}
  3891. #
  3892. #
  3893. #sub _calc_timeout_end {
  3894. #   my IPC::Run $self = shift;
  3895. #
  3896. #   $self->{TIMEOUT_END} = defined $self->{TIMEOUT} 
  3897. #      ? time + $self->{TIMEOUT}
  3898. #      : undef;
  3899. #
  3900. #   ## We add a second because we might be at the very end of the current
  3901. #   ## second, and we want to guarantee that we don't have a timeout even
  3902. #   ## one second less then the timeout period.
  3903. #   ++$self->{TIMEOUT_END} if $self->{TIMEOUT};
  3904. #}
  3905.  
  3906. =pod
  3907.  
  3908. =item io
  3909.  
  3910. Takes a filename or filehandle, a redirection operator, optional filters,
  3911. and a source or destination (depends on the redirection operator).  Returns
  3912. an IPC::Run::IO object suitable for harness()ing (including via start()
  3913. or run()).
  3914.  
  3915. This is shorthand for 
  3916.  
  3917.  
  3918.    require IPC::Run::IO;
  3919.  
  3920.       ... IPC::Run::IO->new(...) ...
  3921.  
  3922. =cut
  3923.  
  3924. sub io {
  3925.    require IPC::Run::IO;
  3926.    IPC::Run::IO->new( @_ );
  3927. }
  3928.  
  3929. =pod
  3930.  
  3931. =item timer
  3932.  
  3933.    $h = start( \@cmd, \$in, \$out, $t = timer( 5 ) );
  3934.  
  3935.    pump $h until $out =~ /expected stuff/ || $t->is_expired;
  3936.  
  3937. Instantiates a non-fatal timer.  pump() returns once each time a timer
  3938. expires.  Has no direct effect on run(), but you can pass a subroutine
  3939. to fire when the timer expires. 
  3940.  
  3941. See L</timeout> for building timers that throw exceptions on
  3942. expiration.
  3943.  
  3944. See L<IPC::Run::Timer/timer> for details.
  3945.  
  3946. =cut
  3947.  
  3948. # Doing the prototype suppresses 'only used once' on older perls.
  3949. sub timer;
  3950. *timer = \&IPC::Run::Timer::timer;
  3951.  
  3952. =pod
  3953.  
  3954. =item timeout
  3955.  
  3956.    $h = start( \@cmd, \$in, \$out, $t = timeout( 5 ) );
  3957.  
  3958.    pump $h until $out =~ /expected stuff/;
  3959.  
  3960. Instantiates a timer that throws an exception when it expires.
  3961. If you don't provide an exception, a default exception that matches
  3962. /^IPC::Run: .*timed out/ is thrown by default.  You can pass in your own
  3963. exception scalar or reference:
  3964.  
  3965.    $h = start(
  3966.       \@cmd, \$in, \$out,
  3967.       $t = timeout( 5, exception => 'slowpoke' ),
  3968.    );
  3969.  
  3970. or set the name used in debugging message and in the default exception
  3971. string:
  3972.  
  3973.    $h = start(
  3974.       \@cmd, \$in, \$out,
  3975.       timeout( 50, name => 'process timer' ),
  3976.       $stall_timer = timeout( 5, name => 'stall timer' ),
  3977.    );
  3978.  
  3979.    pump $h until $out =~ /started/;
  3980.  
  3981.    $in = 'command 1';
  3982.    $stall_timer->start;
  3983.    pump $h until $out =~ /command 1 finished/;
  3984.  
  3985.    $in = 'command 2';
  3986.    $stall_timer->start;
  3987.    pump $h until $out =~ /command 2 finished/;
  3988.  
  3989.    $in = 'very slow command 3';
  3990.    $stall_timer->start( 10 );
  3991.    pump $h until $out =~ /command 3 finished/;
  3992.  
  3993.    $stall_timer->start( 5 );
  3994.    $in = 'command 4';
  3995.    pump $h until $out =~ /command 4 finished/;
  3996.  
  3997.    $stall_timer->reset; # Prevent restarting or expirng
  3998.    finish $h;
  3999.  
  4000. See L</timer> for building non-fatal timers.
  4001.  
  4002. See L<IPC::Run::Timer/timer> for details.
  4003.  
  4004. =cut
  4005.  
  4006. # Doing the prototype suppresses 'only used once' on older perls.
  4007. sub timeout;
  4008. *timeout = \&IPC::Run::Timer::timeout;
  4009.  
  4010. =pod
  4011.  
  4012. =back
  4013.  
  4014. =head1 FILTER IMPLEMENTATION FUNCTIONS
  4015.  
  4016. These functions are for use from within filters.
  4017.  
  4018. =over
  4019.  
  4020. =item input_avail
  4021.  
  4022. Returns TRUE if input is available.  If none is available, then 
  4023. &get_more_input is called and its result is returned.
  4024.  
  4025. This is usually used in preference to &get_more_input so that the
  4026. calling filter removes all data from the $in_ref before more data
  4027. gets read in to $in_ref.
  4028.  
  4029. C<input_avail> is usually used as part of a return expression:
  4030.  
  4031.    return input_avail && do {
  4032.       ## process the input just gotten
  4033.       1;
  4034.    };
  4035.  
  4036. This technique allows input_avail to return the undef or 0 that a
  4037. filter normally returns when there's no input to process.  If a filter
  4038. stores intermediate values, however, it will need to react to an
  4039. undef:
  4040.  
  4041.    my $got = input_avail;
  4042.    if ( ! defined $got ) {
  4043.       ## No more input ever, flush internal buffers to $out_ref
  4044.    }
  4045.    return $got unless $got;
  4046.    ## Got some input, move as much as need be
  4047.    return 1 if $added_to_out_ref;
  4048.  
  4049. =cut
  4050.  
  4051. sub input_avail() {
  4052.    confess "Undefined FBUF ref for $filter_num+1"
  4053.       unless defined $filter_op->{FBUFS}->[$filter_num+1];
  4054.    length ${$filter_op->{FBUFS}->[$filter_num+1]} || get_more_input;
  4055. }
  4056.  
  4057. =pod
  4058.  
  4059. =item get_more_input
  4060.  
  4061. This is used to fetch more input in to the input variable.  It returns
  4062. undef if there will never be any more input, 0 if there is none now,
  4063. but there might be in the future, and TRUE if more input was gotten.
  4064.  
  4065. C<get_more_input> is usually used as part of a return expression,
  4066. see L</input_avail> for more information.
  4067.  
  4068. =cut
  4069.  
  4070. ##
  4071. ## Filter implementation interface
  4072. ##
  4073. sub get_more_input() {
  4074.    ++$filter_num;
  4075.    my $r = eval {
  4076.       confess "get_more_input() called and no more filters in chain"
  4077.          unless defined $filter_op->{FILTERS}->[$filter_num];
  4078.       $filter_op->{FILTERS}->[$filter_num]->(
  4079.          $filter_op->{FBUFS}->[$filter_num+1],
  4080.          $filter_op->{FBUFS}->[$filter_num],
  4081.       ); # if defined ${$filter_op->{FBUFS}->[$filter_num+1]};
  4082.    };
  4083.    --$filter_num;
  4084.    die $@ if $@;
  4085.    return $r;
  4086. }
  4087.  
  4088. 1;
  4089.  
  4090. =pod
  4091.  
  4092. =back
  4093.  
  4094. =head1 TODO
  4095.  
  4096. These will be addressed as needed and as time allows.
  4097.  
  4098. Stall timeout.
  4099.  
  4100. Expose a list of child process objects.  When I do this,
  4101. each child process is likely to be blessed into IPC::Run::Proc.
  4102.  
  4103. $kid->abort(), $kid->kill(), $kid->signal( $num_or_name ).
  4104.  
  4105. Write tests for /(full_)?results?/ subs.
  4106.  
  4107. Currently, pump() and run() only work on systems where select() works on the
  4108. filehandles returned by pipe().  This does *not* include ActiveState on Win32,
  4109. although it does work on cygwin under Win32 (thought the tests whine a bit).
  4110. I'd like to rectify that, suggestions and patches welcome.
  4111.  
  4112. Likewise start() only fully works on fork()/exec() machines (well, just
  4113. fork() if you only ever pass perl subs as subprocesses).  There's
  4114. some scaffolding for calling Open3::spawn_with_handles(), but that's
  4115. untested, and not that useful with limited select().
  4116.  
  4117. Support for C<\@sub_cmd> as an argument to a command which
  4118. gets replaced with /dev/fd or the name of a temporary file containing foo's
  4119. output.  This is like <(sub_cmd ...) found in bash and csh (IIRC).
  4120.  
  4121. Allow multiple harnesses to be combined as independent sets of processes
  4122. in to one 'meta-harness'.
  4123.  
  4124. Allow a harness to be passed in place of an \@cmd.  This would allow
  4125. multiple harnesses to be aggregated.
  4126.  
  4127. Ability to add external file descriptors w/ filter chains and endpoints.
  4128.  
  4129. Ability to add timeouts and timing generators (i.e. repeating timeouts).
  4130.  
  4131. High resolution timeouts.
  4132.  
  4133. =head1 Win32 LIMITATIONS
  4134.  
  4135. =over
  4136.  
  4137. =item Fails on Win9X
  4138.  
  4139. If you want Win9X support, you'll have to debug it or fund me because I
  4140. don't use that system any more.  The Win32 subsysem has been extended to
  4141. use temporary files in simple run() invocations and these may actually
  4142. work on Win9X too, but I don't have time to work on it.
  4143.  
  4144. =item May deadlock on Win2K (but not WinNT4 or WinXPPro)
  4145.  
  4146. Spawning more than one subprocess on Win2K causes a deadlock I haven't
  4147. figured out yet, but simple uses of run() often work.  Passes all tests
  4148. on WinXPPro and WinNT.
  4149.  
  4150. =item no support yet for <pty< and >pty>
  4151.  
  4152. These are likely to be implemented as "<" and ">" with binmode on, not
  4153. sure.
  4154.  
  4155. =item no support for file descriptors higher than 2 (stderr)
  4156.  
  4157. Win32 only allows passing explicit fds 0, 1, and 2.  If you really, really need to pass file handles, us Win32API:: GetOsFHandle() or ::FdGetOsFHandle() to
  4158. get the integer handle and pass it to the child process using the command
  4159. line, environment, stdin, intermediary file, or other IPC mechnism.  Then
  4160. use that handle in the child (Win32API.pm provides ways to reconstitute
  4161. Perl file handles from Win32 file handles).
  4162.  
  4163. =item no support for subroutine subprocesses (CODE refs)
  4164.  
  4165. Can't fork(), so the subroutines would have no context, and closures certainly
  4166. have no meaning
  4167.  
  4168. Perhaps with Win32 fork() emulation, this can be supported in a limited
  4169. fashion, but there are other very serious problems with that: all parent
  4170. fds get dup()ed in to the thread emulating the forked process, and that
  4171. keeps the parent from being able to close all of the appropriate fds.
  4172.  
  4173. =item no support for init => sub {} routines.
  4174.  
  4175. Win32 processes are created from scratch, there is no way to do an init
  4176. routine that will affect the running child.  Some limited support might
  4177. be implemented one day, do chdir() and %ENV changes can be made.
  4178.  
  4179. =item signals
  4180.  
  4181. Win32 does not fully support signals.  signal() is likely to cause errors
  4182. unless sending a signal that Perl emulates, and C<kill_kill()> is immediately
  4183. fatal (there is no grace period).
  4184.  
  4185. =item helper processes
  4186.  
  4187. IPC::Run uses helper processes, one per redirected file, to adapt between the
  4188. anonymous pipe connected to the child and the TCP socket connected to the
  4189. parent.  This is a waste of resources and will change in the future to either
  4190. use threads (instead of helper processes) or a WaitForMultipleObjects call
  4191. (instead of select).  Please contact me if you can help with the
  4192. WaitForMultipleObjects() approach; I haven't figured out how to get at it
  4193. without C code.
  4194.  
  4195. =item shutdown pause
  4196.  
  4197. There seems to be a pause of up to 1 second between when a child program exits
  4198. and the corresponding sockets indicate that they are closed in the parent.
  4199. Not sure why.
  4200.  
  4201. =item binmode
  4202.  
  4203. binmode is not supported yet.  The underpinnings are implemented, just ask
  4204. if you need it.
  4205.  
  4206. =item IPC::Run::IO
  4207.  
  4208. IPC::Run::IO objects can be used on Unix to read or write arbitrary files.  On
  4209. Win32, they will need to use the same helper processes to adapt from
  4210. non-select()able filehandles to select()able ones (or perhaps
  4211. WaitForMultipleObjects() will work with them, not sure).
  4212.  
  4213. =item startup race conditions
  4214.  
  4215. There seems to be an occasional race condition between child process startup
  4216. and pipe closings.  It seems like if the child is not fully created by the time
  4217. CreateProcess returns and we close the TCP socket being handed to it, the
  4218. parent socket can also get closed.  This is seen with the Win32 pumper
  4219. applications, not the "real" child process being spawned.
  4220.  
  4221. I assume this is because the kernel hasn't gotten around to incrementing the
  4222. reference count on the child's end (since the child was slow in starting), so
  4223. the parent's closing of the child end causes the socket to be closed, thus
  4224. closing the parent socket.
  4225.  
  4226. Being a race condition, it's hard to reproduce, but I encountered it while
  4227. testing this code on a drive share to a samba box.  In this case, it takes
  4228. t/run.t a long time to spawn it's chile processes (the parent hangs in the
  4229. first select for several seconds until the child emits any debugging output).
  4230.  
  4231. I have not seen it on local drives, and can't reproduce it at will,
  4232. unfortunately.  The symptom is a "bad file descriptor in select()" error, and,
  4233. by turning on debugging, it's possible to see that select() is being called on
  4234. a no longer open file descriptor that was returned from the _socket() routine
  4235. in Win32Helper.  There's a new confess() that checks for this ("PARENT_HANDLE
  4236. no longer open"), but I haven't been able to reproduce it (typically).
  4237.  
  4238. =back
  4239.  
  4240. =head1 LIMITATIONS
  4241.  
  4242. On Unix, requires a system that supports C<waitpid( $pid, WNOHANG )> so
  4243. it can tell if a child process is still running.
  4244.  
  4245. PTYs don't seem to be non-blocking on some versions of Solaris. Here's a
  4246. test script contributed by Borislav Deianov <borislav@ensim.com> to see
  4247. if you have the problem.  If it dies, you have the problem.
  4248.  
  4249.    #!/usr/bin/perl
  4250.  
  4251.    use IPC::Run qw(run);
  4252.    use Fcntl;
  4253.    use IO::Pty;
  4254.  
  4255.    sub makecmd {
  4256.        return ['perl', '-e', 
  4257.                '<STDIN>, print "\n" x '.$_[0].'; while(<STDIN>){last if /end/}'];
  4258.    }
  4259.  
  4260.    #pipe R, W;
  4261.    #fcntl(W, F_SETFL, O_NONBLOCK);
  4262.    #while (syswrite(W, "\n", 1)) { $pipebuf++ };
  4263.    #print "pipe buffer size is $pipebuf\n";
  4264.    my $pipebuf=4096;
  4265.    my $in = "\n" x ($pipebuf * 2) . "end\n";
  4266.    my $out;
  4267.  
  4268.    $SIG{ALRM} = sub { die "Never completed!\n" };
  4269.  
  4270.    print "reading from scalar via pipe...";
  4271.    alarm( 2 );
  4272.    run(makecmd($pipebuf * 2), '<', \$in, '>', \$out);
  4273.    alarm( 0 );
  4274.    print "done\n";
  4275.  
  4276.    print "reading from code via pipe... ";
  4277.    alarm( 2 );
  4278.    run(makecmd($pipebuf * 3), '<', sub { $t = $in; undef $in; $t}, '>', \$out);
  4279.    alarm( 0 );
  4280.    print "done\n";
  4281.  
  4282.    $pty = IO::Pty->new();
  4283.    $pty->blocking(0);
  4284.    $slave = $pty->slave();
  4285.    while ($pty->syswrite("\n", 1)) { $ptybuf++ };
  4286.    print "pty buffer size is $ptybuf\n";
  4287.    $in = "\n" x ($ptybuf * 3) . "end\n";
  4288.  
  4289.    print "reading via pty... ";
  4290.    alarm( 2 );
  4291.    run(makecmd($ptybuf * 3), '<pty<', \$in, '>', \$out);
  4292.    alarm(0);
  4293.    print "done\n";
  4294.  
  4295. No support for ';', '&&', '||', '{ ... }', etc: use perl's, since run()
  4296. returns TRUE when the command exits with a 0 result code.
  4297.  
  4298. Does not provide shell-like string interpolation.
  4299.  
  4300. No support for C<cd>, C<setenv>, or C<export>: do these in an init() sub
  4301.  
  4302.    run(
  4303.       \cmd,
  4304.          ...
  4305.          init => sub {
  4306.             chdir $dir or die $!;
  4307.             $ENV{FOO}='BAR'
  4308.          }
  4309.    );
  4310.  
  4311. Timeout calculation does not allow absolute times, or specification of
  4312. days, months, etc.
  4313.  
  4314. B<WARNING:> Function coprocesses (C<run \&foo, ...>) suffer from two
  4315. limitations.  The first is that it is difficult to close all filehandles the
  4316. child inherits from the parent, since there is no way to scan all open
  4317. FILEHANDLEs in Perl and it both painful and a bit dangerous to close all open
  4318. file descriptors with C<POSIX::close()>. Painful because we can't tell which
  4319. fds are open at the POSIX level, either, so we'd have to scan all possible fds
  4320. and close any that we don't want open (normally C<exec()> closes any
  4321. non-inheritable but we don't C<exec()> for &sub processes.
  4322.  
  4323. The second problem is that Perl's DESTROY subs and other on-exit cleanup gets
  4324. run in the child process.  If objects are instantiated in the parent before the
  4325. child is forked, the the DESTROY will get run once in the parent and once in
  4326. the child.  When coprocess subs exit, POSIX::exit is called to work around this,
  4327. but it means that objects that are still referred to at that time are not
  4328. cleaned up.  So setting package vars or closure vars to point to objects that
  4329. rely on DESTROY to affect things outside the process (files, etc), will
  4330. lead to bugs.
  4331.  
  4332. I goofed on the syntax: "<pipe" vs. "<pty<" and ">filename" are both
  4333. oddities.
  4334.  
  4335. =head1 TODO
  4336.  
  4337. =over
  4338.  
  4339. =item Allow one harness to "adopt" another:
  4340.  
  4341.    $new_h = harness \@cmd2;
  4342.    $h->adopt( $new_h );
  4343.  
  4344. =item Close all filehandles not explicitly marked to stay open.
  4345.  
  4346. The problem with this one is that there's no good way to scan all open
  4347. FILEHANDLEs in Perl, yet you don't want child processes inheriting handles
  4348. willy-nilly.
  4349.  
  4350. =back
  4351.  
  4352. =head1 INSPIRATION
  4353.  
  4354. Well, select() and waitpid() badly needed wrapping, and open3() isn't
  4355. open-minded enough for me.
  4356.  
  4357. The shell-like API inspired by a message Russ Allbery sent to perl5-porters,
  4358. which included:
  4359.  
  4360.    I've thought for some time that it would be
  4361.    nice to have a module that could handle full Bourne shell pipe syntax
  4362.    internally, with fork and exec, without ever invoking a shell.  Something
  4363.    that you could give things like:
  4364.  
  4365.    pipeopen (PIPE, [ qw/cat file/ ], '|', [ 'analyze', @args ], '>&3');
  4366.  
  4367. Message ylln51p2b6.fsf@windlord.stanford.edu, on 2000/02/04.
  4368.  
  4369. =head1 SUPPORT
  4370.  
  4371. Bugs should always be submitted via the CPAN bug tracker
  4372.  
  4373. L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=IPC-Run>
  4374.  
  4375. For other issues, contact the maintainer (the first listed author)
  4376.  
  4377. =head1 AUTHORS
  4378.  
  4379. Adam Kennedy <adamk@cpan.org>
  4380.  
  4381. Barrie Slaymaker <barries@slaysys.com>
  4382.  
  4383. =head1 COPYRIGHT
  4384.  
  4385. Some parts copyright 2008 - 2009 Adam Kennedy.
  4386.  
  4387. Copyright 1999 Barrie Slaymaker.
  4388.  
  4389. You may distribute under the terms of either the GNU General Public
  4390. License or the Artistic License, as specified in the README file.
  4391.  
  4392. =cut
  4393.